我正在尝试更改datagridview列中单元格的值,具体取决于同一datagridview中添加的组合框列中的选择。
我已经使用了各种各样的BindingSources,但似乎没有什么能让它变得非常正确。
我正在使用的代码是:
conn = new SqlConnection(DBConnectionString);
select_order = new SqlCommand("SELECT orderNum, orderBy, orderShipadrs, orderDate FROM tblOrders WHERE orderNum=" + OrderID, conn);
da1 = new SqlDataAdapter(select_order);
select_lines = new SqlCommand("SELECT linenum, fkprdctnum, lineQuantity, lineprdctPrice FROM tblOrderLines WHERE fkOrdernum=" + OrderID, conn);
da2 = new SqlDataAdapter(select_lines);
da2.MissingSchemaAction = MissingSchemaAction.AddWithKey;
select_products = new SqlCommand("SELECT * FROM tblProducts", conn);
da3 = new SqlDataAdapter(select_products);
Orders = new DataSet();
try
{
da1.Fill(Orders, Order);
da2.Fill(Orders, Lines);
da3.Fill(Orders, Products);
}
catch
{
MessageBox.Show("There was an error connecting to the database.");
}
DataRelation prdctprice = new DataRelation(Relations, Orders.Tables[Products].Columns["prdctNum"], Orders.Tables[Lines].Columns["fkPrdctnum"]);
Orders.Relations.Add(prdctprice);
CurrentOrder.DataSource = Orders.Tables[Order];
CurrentOrder.Columns["orderNum"].HeaderText = "Number";
CurrentOrder.Columns["orderNum"].Width = 50;
CurrentOrder.Columns["orderBy"].HeaderText = "Customer Name";
CurrentOrder.Columns["orderBy"].Width = 150;
CurrentOrder.Columns["orderShipadrs"].HeaderText = "Shipping Address";
CurrentOrder.Columns["orderShipadrs"].Width = 200;
CurrentOrder.Columns["orderDate"].HeaderText = "Order Date";
CurrentOrder.Columns["orderDate"].Width = 100;
//masterBindingSource.DataSource = Orders;
//masterBindingSource.DataMember = Products;
CurrentLine.DataSource = Orders.Tables["Lines"];
DataGridViewComboBoxColumn prod = new DataGridViewComboBoxColumn();
prod.DataSource = Orders.Tables[Products];
prod.DisplayMember = "prdctName";
prod.ValueMember = "prdctNum";
prod.HeaderText = "Product";
CurrentLine.Columns.Add(prod);
//detailBindingSource.DataSource = masterBindingSource;
//detailBindingSource.DataMember = Relations;
CurrentLine.Columns["fkPrdctnum"].Visible = false;
CurrentLine.Columns["linenum"].Width = 60;
CurrentLine.Columns["linenum"].HeaderText = "Number";
CurrentLine.Columns["linenum"].ReadOnly = true;
CurrentLine.Columns["lineQuantity"].HeaderText = "Quantity";
CurrentLine.Columns["lineQuantity"].Width = 70;
CurrentLine.Columns["linePrdctPrice"].HeaderText = "Price";
CurrentLine.Columns["linePrdctPrice"].ReadOnly = true;
只是让你有一个视觉效果,让它变得简单: 我希望“价格”列中的单元格根据“产品”组合框中的选项进行更改。 组合框从数据集中名为“Products”的表中获取数据,而数据网格的其余部分从名为“Lines”的表中获取数据。
问题是,我唯一的选择是删除“价格”列并手动添加另一个将随组合框更改的列?如果没有,我还有其他选择吗?
答案 0 :(得分:1)
之前我还没有在数据网格中使用过组合框,但是如果你能改变组合框索引,那么看看你是否可以有一个事件处理程序可能是个好主意。每次更改时更新数据网格。如果不可能,则可以将其作为单独的组合框执行,并在表单加载时将其与产品一起填充,然后每次选择产品时,它都会更新网格视图以显示价格和数量。另外,从个人视觉标准开始,我会在产品名称开头,但这是我个人的偏好。希望这有帮助。