我有一个包含id
,office
,transpo
和allowance
列的表格。现在我的代码就是这样。
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();
我的问题是,在我的表格中,我还有transpo
和allowance
列。每当在显示的组合框中挑选出office
列时,我如何在变量中传递适当的值?
答案 0 :(得分:0)
要获取与组合框选择对应的值,请通过以下代码:
1.使数据表可以在函数外部访问,因此使用全局方面定义它。
DataTable dt = new DataTable();
使用您的函数填充数据表。
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();
}
获取按钮单击或组合框选择更改时的组合框值
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);
}