伙计我真的需要你的帮助。我收到上述标题的错误。所有尝试做的是当datagridview被点击时它应该在文本框中显示所选记录以及打开它新表单。这是我的代码。
using System.Data;
using System.Data.SqlClient;
namespace DataGridview
{
public partial class FrmDataGrid : Form
{
SqlConnection con = new SqlConnection("ConnectionString");
public FrmDataGrid()
{
InitializeComponent();
}
private void FrmDataGrid_Load(object sender, EventArgs e)
{
try {
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM UserData";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
textBox1.Text = dataGridView1.SelectedRows[0].Cells["UserID"].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[1].Cells["FullName"].Value.ToString();
textBox3.Text = dataGridView1.SelectedRows[2].Cells["Username"].Value.ToString();
textBox4.Text = dataGridView1.SelectedRows[3].Cells["UserPassword"].Value.ToString();
textBox5.Text = dataGridView1.SelectedRows[4].Cells["UserRole"].Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
FrmUpdate FormUpdate = new FrmUpdate();
FormUpdate.ShowDialog();
}
}
}
答案 0 :(得分:0)
在其中一个调用期间,您最有可能选择超出范围的行:
dataGridView1.SelectedRows[0]
答案 1 :(得分:0)
您尝试获取5行,甚至没有检查数据库查询结果中是否存在5行。我认为您正在尝试获取一行的5列,因此请根据您的要求使用以下代码:
textBox1.Text = dataGridView1.SelectedRows[0].Cells["UserID"].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[0].Cells["FullName"].Value.ToString();
textBox3.Text = dataGridView1.SelectedRows[0].Cells["Username"].Value.ToString();
textBox4.Text = dataGridView1.SelectedRows[0].Cells["UserPassword"].Value.ToString();
textBox5.Text = dataGridView1.SelectedRows[0].Cells["UserRole"].Value.ToString();