如何将值从datagridview传递到文本框

问题描述

我目前正在系统上工作。我有一个带有上下文菜单的datagridview和一个编辑和删除按钮。当我单击上下文菜单上的编辑时,我想将所选行的值传递到文本框。

我已成功将值传递到文本框,但显示的唯一值是从最后输入的数据到我单击的任何行。我不知道如何获取ID,有人可以帮我解决问题吗? :(

这是我的代码

private void BtnEdit_Click(object sender,EventArgs e)
{
    frmAddEditStudent frm = new frmAddEditStudent(this);

    cn.open();
    cm = new sqlCommand("SELECT s.studentID,s.studentNo,s.Lname,s.Fname,s.MI,s.gender,s.yearLevel,s.section,s.studImage,g.name,g.contactNo,g.address FROM Student s INNER JOIN Guardian g ON g.studentNo = s.studentNo WHERE g.studentNo = s.studentNo AND s.isActive = 'true' AND s.studentID = studentID",cn);
    cm.Parameters.AddWithValue("studentID",lblID.Text);

    for (int i = 0; i < guna2DataGridView1.Rows.Count; i += 1)
    {
        frm.btnSave.Enabled = false;
        frm.lblTitle.Text = "Edit Student Details";
        frm.lblID.Text = guna2DataGridView1.Rows[i].Cells[1].Value.ToString();
        frm.txtStudentNo.Text = guna2DataGridView1.Rows[i].Cells[2].Value.ToString();
        frm.txtLname.Text = guna2DataGridView1.Rows[i].Cells[3].Value.ToString();
        frm.txtFname.Text = guna2DataGridView1.Rows[i].Cells[4].Value.ToString();
        frm.txtMI.Text = guna2DataGridView1.Rows[i].Cells[5].Value.ToString();
        frm.cboGradeLevel.Text = guna2DataGridView1.Rows[i].Cells[7].Value.ToString();
        frm.cboSection.Text = guna2DataGridView1.Rows[i].Cells[8].Value.ToString();
        frm.txtGuardianName.Text = guna2DataGridView1.Rows[i].Cells[9].Value.ToString();
        frm.txtContactNo.Text = guna2DataGridView1.Rows[i].Cells[10].Value.ToString();
        frm.txtAddress.Text = guna2DataGridView1.Rows[i].Cells[11].Value.ToString();

        //Load Image
        byte[] bytes = (byte[])guna2DataGridView1.Rows[i].Cells[12].Value;
        MemoryStream ms = new MemoryStream(bytes);
        frm.studImage.Image = Image.FromStream(ms);

        //Retrieve gender value to radio button
        if (guna2DataGridView1.Rows[i].Cells[6].Value.ToString() == "Male")
        {
            frm.rbMale.Checked = true;
        }
        else
        {
            frm.rbFemale.Checked = true;
        }

    }
    cn.Close();
    frm.ShowDialog();

它不会在我选择的行中显示数据,而是仅显示数据库表中的最后一行。

解决方法

您可以通过以下方式从datagridview获取当前行或选定的行(我认为ID是具有索引1的单元格):

Console.WriteLine(guna2DataGridView1.CurrentRow.Cells[1].Value.ToString());

foreach (DataGridViewRow loRow in guna2DataGridView1.CurrentRow.SelectedRows)
{
    Console.WriteLine(loRow.Cells[1].Value.ToString());
}   

但是您每次都会覆盖循环中的表单值。 您的表单似乎只能显示一行,而不能显示一个集合。 而命令cm呢?