我对编程和 c# 很陌生。在这里,我遇到了 ArguementOutOfRangeException。每次单击按钮时,我都想向 datagridview 添加一个新数据行。所以我使用变量“i”来逐一增加值并在我使用“0”时更改行值,这意味着
dataGridView2.Rows[0].Cells[0].Value = textBox1.Text.ToString();
而不是“i”第一行填充但是当使用“1”时,这意味着
dataGridView2.Rows[1].Cells[0].Value = textBox1.Text.ToString();
例外来了。做这种事情的正确方法是什么?
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public SqlConnection conn;
public int i = 0;
private void Form2_Load(object sender, EventArgs e)
{
conn = new SqlConnection("Data Source=.\\SQLEXPRESS; Integrated Security=sspi; Initial Catalog=student");
conn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
string Sqlstr = "insert into student(name, pw)values(@name,@pw)";
SqlCommand cmd = new SqlCommand(Sqlstr, conn);
cmd.Parameters.AddWithValue("@name", textBox1.Text);
cmd.Parameters.AddWithValue("@pw", textBox2.Text);
if (cmd.ExecuteNonQuery() > 0)
{
i++;
DataGridView dataGridView1 = new DataGridView();
dataGridView2.Rows[i].Cells[0].Value = textBox1.Text.ToString();
dataGridView2.Rows[i].Cells[1].Value = textBox2.Text.ToString();
}
label1.Text = Convert.ToString(i);
}
}
}