如何根据另一个列字段获取列字段的值

Posted

技术标签:

【中文标题】如何根据另一个列字段获取列字段的值【英文标题】:How can i get the value of column field base on another column field 【发布时间】:2016-08-11 02:32:46 【问题描述】:

我使用 Visual Studio C# 并使用 Access 作为我的数据库。我有两列,ItemCodeProductName。我想在选择其itemcode时自动在其TextBox上自动输入。我怎样才能做到这一点?

一些代码:

 try
 
 con.Open();
 OleDbCommand command = new OleDbCommand(@"Select * from TblInventory where ItemCode='" + txtItem.Text + "'");
 command.Connection = con;
 command.Parameters.AddWithValue("itemcode", txtItem.Text);

 OleDbDataReader reader = command.ExecuteReader();
 if (reader.Read())//Update Item Code is already exist
    
     .........

请随意编辑我的问题,请善待。谢谢各位

【问题讨论】:

你的意思是在选择itemcode时自动输入productname,我希望你想更新product_name对应where子句中的id,不是吗? 是的,我想获取产品名称的值并在我的文本框中调用它,该文本框对应于该项目代码的同一行 我会至少将 ItemCode 和 ProductName 对加载到 DataTable,然后将 bind DataTable 加载到您用于显示和选择 itemcode 和 productname 的任何控件中。请记住,您可以绑定one data source to multiple controls。根据需要为每个控件调整 DisplayMember。 【参考方案1】:

试试这个。

text_box.Text=reader["ProductName"].ToString();

您正在通过在Where 子句中指定ItemCode 来过滤行,因此阅读器将包含与指定代码匹配的相应行。您需要做的是通过像上面的 sn-p 一样指定名称来访问所需的列值。

【讨论】:

【参考方案2】:

为了从数据库中提取数据,我更喜欢使用OleDbDataAdapter。 您可以简单地使用:

string command = @"Select * from TblInventory where ItemCode='" + txtItem.Text + "'";
OleDbDataAdapter da = new OleDbDataAdapter(command, con);
DataTable dt = new DataTable();
da.Fill(dt);

现在,使用dt

if (dt.Rows.Count == 0)
    //Error Message
else
    cmbTreatyTitle.Text = dt.Rows[0]["ProductName"].ToString();

我希望这会有所帮助。

【讨论】:

以上是关于如何根据另一个列字段获取列字段的值的主要内容,如果未能解决你的问题,请参考以下文章

如何使用来自另一个表列的值优化列的更新?

BigQuery:如何获取列中特定字段的值?

根据另一个字段的值启用/禁用对某些字段的输入

怎么根据一个表的字段值修改另一个表的字段值

layui数据表格如何根据列名修改整列的值?

根据另一列自动填充 excel 中的字段