我希望在C#中的datagridview中添加列时生成动态文本框和标签。 我还希望稍后编写一个SQL查询,它将我新生成的textBox作为参数/新列名。发生的错误显示“参数超出范围异常未得到处理”。
请帮忙
public void CreateLabels()
{
Label lb = new Label();
this.Controls.Add(lb);
int p= dataGridView1.ColumnCount;
for (int k = p; k <= dataGridView1.ColumnCount; k++)
{
for (int z =p; z <= dataGridView1.ColumnCount; z++)
{
dataGridView1.Refresh();
lb.Text = dataGridView1.Columns[z++].HeaderText;
}
lb.Show();
lb.Visible = true;
}
lb.Location = new Point(m,n=n+25);
lb.Width = 199;
lb.Height = 20;
}
public void CreateTextBoxes()
{
TextBox tb = new TextBox();
this.Controls.Add(tb);
for (int i = 5; i <= dataGridView1.ColumnCount; i++)
{
dataGridView1.Refresh();
tb.Name = "textBox" + i;
MessageBox.Show(tb.Name);
}
tb.Location = new Point(x, y = y + 25);
tb.Show();
tb.Visible = true;
}*/
//Below method is used to get data in datagridview1 and to reflect in runtime text boxes and labels;the visible property is kept false
/*private void displayRec()
{
try
{
string str = System.Environment.MachineName;
SqlConnection sconn = new SqlConnection("Data Source='" + str + "';Initial Catalog=main;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select * from invent", sconn);
da.Fill(dt);
dataGridView1.DataSource = dt.DefaultView;
//dataGridView1.Refresh();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
答案 0 :(得分:0)
说实话,我不明白你的循环的想法。它们具有相同的条件而你从不使用'k';
然而,两个循环都是从最后一列+1开始;在lb.Text的赋值中,您试图获取不存在的列的HeaderText。这就是你超出范围异常的原因。