【问题标题】:Adding hidden value of a column in SQL Server using C# in combobox在组合框中使用 C# 在 SQL Server 中添加列的隐藏值
【发布时间】:2017-04-26 20:09:32
【问题描述】:

在 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 列)中选择什么时,如何在变量中传输适当的值?

【问题讨论】:

  • 试试SelectedValue

标签: c# sql-server winforms combobox


【解决方案1】:

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

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);
    }
    

【讨论】:

  • 如果您发现它有效,请将其标记为已回答,以便对其他人也有帮助....如果您有任何疑问或问题,请随时联系我。
  • 我使用了你的方法,它根据我的实际需要工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-10-24
  • 2016-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多