我有一个按钮,可以为TableLayoutPanel的列创建6个控件,这6列是:订单号,产品名称(组合框),当前数量(标签 >),购买数量,新数量和删除行。
使用SQLite填充组合框。对于“变量”表,我有7列:[产品名称],名称,[序列号],[现有库存],[先售后]。
如何使“当前数量”下的标签根据组合框上所选项目的“现有库存”而变化?
在我当前的代码上,每次我在组合框中选择时,都会显示错误“索引在数组的边界之外”。
用于创建动态组合框的代码:
ComboBox cboItemName = new ComboBox
{
Name = "cboItemName" + rowIndex,
Dock = DockStyle.Fill,
DropDownStyle = ComboBoxStyle.DropDownList
};
cboItemName.SelectedIndexChanged += new EventHandler(cboItemName_SelectedIndexChanged);
tblOrders.Controls.Add(FillComboBox(cboItemName));
组合框的事件处理程序的代码:
void cboItemName_SelectedIndexChanged(object sender, EventArgs e)
{
var cbo = (ComboBox)sender;
string name = cbo.Name;
string splittedString = new String(name.Where(Char.IsDigit).ToArray());;
string labelName = "lblCurrentQuantity" + splittedString;
string selectedIndex = cbo.SelectedIndex.ToString();
string selectedItem = cbo.SelectedItem.ToString();
Label tbx = tblOrders.Controls.Find(labelName, true).FirstOrDefault() as Label;
EditLabelCurrentQuantity(tbx, selectedItem);
}
最后,是用于更改标签文本的代码:
private void EditLabelCurrentQuantity(Label label, string itemSelected)
{
auth = new Authentication();
auth.getConnection();
try
{
using (SQLiteConnection con = new SQLiteConnection(auth.connectionString))
{
con.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.CommandText = @"SELECT [Stock On Hand] FROM Variants WHERE Name='" + itemSelected + "'";
cmd.Connection = con;
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = Convert.ToString(reader["[Stock On Hand]"]);
}
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
答案 0 :(得分:0)
我终于弄清楚了,如果有人遇到过我的不良设计,我可以通过添加以下内容来解决:
string name = Convert.ToString(reader[0]);
labelCategory.Text = name;
在:
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = Convert.ToString(reader["[Stock On Hand]"]);
}