当我检查CheckBoxList
中想要从SQL
table
中哪些列的项目时,我正在制作一个表格,我得到一个new Form()
,在那里我想添加值并将其添加到SQL。除了最后一个,我得到空值。有什么建议吗?
private void Button1_Click(object sender, EventArgs e)
{
query = $"INSERT INTO {DM.comboBox1.SelectedItem} Values(";
for (int i = 0; i <DM.checkedListBox1.CheckedIndices.Count; i++)
{
if (DM.checkedListBox1.CheckedIndices.Count == i + 1)
{
query += "'" + txtBox[i].Text + "')";
break;
}
query += "'" + txtBox[i].Text + "'";
query += ",";
}
myQuery = query;
Fm1.conn = new SqlConnection($"Server = {Fm1.ServerBox.Text }; Database = { Fm1.DBBox.Text}; Trusted_Connection = True");
Fm1.cmd = new SqlCommand(myQuery, Fm1.conn);
Fm1.conn.Open();
Fm1.cmd.ExecuteNonQuery();
Fm1.conn.Close();
}
private void Test_Load(object sender, EventArgs e)
{
TableLayoutPanel tableLayoutPanel = new TableLayoutPanel() { AutoSize = true };
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
int n = 0;
for (int i = 0; i < DM.checkedListBox1.CheckedItems.Count; i++)
{
txtBox = new TextBox[DM.checkedListBox1.CheckedItems.Count];
labels = new Label[DM.checkedListBox1.CheckedItems.Count];
labels[i] = new Label();
for (int j = i; j < DM.dataGridView1.Columns.Count; j++)
{
if (DM.dataGridView1.Columns[j].Visible)
{
labels[i].Text = DM.dataGridView1.Columns[j].HeaderText;
break;
}
}
tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
tableLayoutPanel.SetCellPosition(labels[i], new TableLayoutPanelCellPosition(0, n++));
tableLayoutPanel.Controls.Add(labels[i]);
txtBox[i] = new TextBox();
tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
tableLayoutPanel.SetCellPosition(txtBox[i], new TableLayoutPanelCellPosition(0, n++));
tableLayoutPanel.Controls.Add(txtBox[i]);
}
Controls.Add(tableLayoutPanel);
}
答案 0 :(得分:1)
不能评论,因为没有50。上面的艾米是正确的。
删除这些行,然后重试:
labels = new Label[DM.checkedListBox1.CheckedItems.Count];
txtBox = new TextBox[DM.checkedListBox1.CheckedItems.Count];
由于评论而更新。