[英]DataGridview Combobox display from datasource
我的數據庫中有兩個表
數據表有兩列產品,產品類型。 kar表也有兩列類型,tax。
在我的表單中,我有一個Datagridview,其中有3列產品名,類型,稅。
Productname列是datagridviewcomboboxcolumn,它顯示數據表中的所有產品。 `
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
this.datatableTableAdapter.Fill(this.myBillDataSet.datatable);
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
string item = null;
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=ZEE-PC\SQLEXPRESS;Initial Catalog=MyBill;Integrated Security=True");
ComboBox cb = (ComboBox)sender;
item = cb.Text;
if (item != null)
{
SqlCommand cmd = new SqlCommand("select Producttype from datatable where product=@pro", con);
cmd.Parameters.AddWithValue("@pro", item);
con.Open();
string val = cmd.ExecuteScalar().ToString();
con.Close();
SqlCommand cmd2 = new SqlCommand("select tax from kar where type=@pro2", con);
cmd2.Parameters.AddWithValue("@pro2", val);
con.Open();
string val2 = cmd2.ExecuteScalar().ToString();
con.Close();
}
}
當用戶從下拉列表中選擇任何產品時,類型和稅項列將顯示該值。 我正在獲取值,但無法在gridview單元中顯示
您可以使用列索引將值直接插入ComboBox_SelectedIndexChanged事件內的單元格中
dataGridView1.Rows[e.RowIndex].Cells[YourCellindex] = val;
dataGridView1.Rows[e.RowIndex].Cells[YourSecondCellindex] = val2;
dataGridView1.BeginEdit(true);
dataGridView1.EndEdit();
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.