使用组合框中的C#在SQL Server中添加列的隐藏值

时间:2016-12-12 00:34:57

标签: c# sql-server winforms combobox

SQL Server中的

我有一个包含idofficetranspoallowance列的表格。现在我的代码就是这样。

  using (SqlConnection conn = new SqlConnection("Data Source=PC; Initial Catalog=DATABASE; Integrated Security=True"))
            {
conn.Open();
SqlCommand sc = new SqlCommand("select * from branch order by office asc", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("OFFICE", typeof(string));
dt.Load(reader);
comboboxDestination.ValueMember = "ID";
comboboxDestination.DisplayMember = "OFFICE";
comboboxDestination.DataSource = dt;
conn.Close();
            }

现在它显示确定,我可以将组合框中的内容转移到我用来做的其他形式。

 string destination;
 destination = comboboxDestination.Text.ToString();

我的问题是,在我的表格中,我还有transpoallowance列。每当在显示的组合框中挑选出office列时,我如何在变量中传递适当的值?

1 个答案:

答案 0 :(得分:0)

要获取与组合框选择对应的值,请通过以下代码:

1.使数据表可以在函数外部访问,因此使用全局方面定义它。

DataTable dt = new DataTable();
  1. 使用您的函数填充数据表。

    using (SqlConnection conn = new SqlConnection("Data Source=PC; Initial Catalog=DATABASE; Integrated Security=True"))
    {
        conn.Open();
        SqlCommand sc = new SqlCommand("select * from branch order by office asc", conn);
        SqlDataReader reader = sc.ExecuteReader();
        dt.Columns.Add("ID", typeof(string));
        dt.Columns.Add("OFFICE", typeof(string));
        dt.Load(reader);
        comboboxDestination.ValueMember = "ID";
        comboboxDestination.DisplayMember = "OFFICE";
        comboboxDestination.DataSource = dt;
        conn.Close();
    }
    
  2. 获取按钮单击或组合框选择更改时的组合框值

    private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        string destination="";
        string transpo="";
        string allowance="";
        destination = comboboxDestination.Text.ToString();
    
       //Function to get values regarding selected combo box value.
       foreach(DataRow row in dt.Rows)
       {
           if(row["OFFICE"].ToString().ToUpper() == destination.ToUpper())
           {
               transpo=row["Transpo"].ToString();
               allowance=row["Allowance"].ToString();
               break;
           }
       }
       Console.Write("Transpo = "+ transpo);
       Console.Write("Allowance= "+ allowance);
    }