小编典典

单击数据网格行并在文本框中显示其内容

sql

我正在尝试使用数据网格的内容填充文本框。

我正在使用一个名为XYZCompany.accbd的数据源。我用数据库的内容填充dgv,在这种情况下,包含供应商ID(自动编号字段),供应商名称,供应商地址,电话号码和合同名称。

首先,我用这些字段填充dgv。然后,我要努力的下一步是,当我单击dgv中的一行时,它应该在文本框中显示该行的数据。问题是,当我单击dgv行时,在文本框中没有显示任何内容,并且没有收到任何错误。

我将连接作为参数传递给新表单。但是我还是会指定它。这是我通过的声明:

    OleDbConnection dbConn;
    OleDbCommand dbCmd;
    DataSet ds = new DataSet();
    OleDbDataAdapter dbAdapter;
    private void ViewAllSuppliers_Load(object sender, EventArgs e)
    {
        dbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data     Source=XYZCompany.accdb");

        dbCmd = new OleDbCommand("SELECT * FROM Supplier ORDER BY [Supplier ID]", dbConn);


        dbAdapter = new OleDbDataAdapter(dbCmd);
        dbAdapter.Fill(ds, "Suppliers");

    }

    private void btnViewSuppliers_Click(object sender, EventArgs e)
    {
        dgvSuppliers.DataSource = ds.Tables["Suppliers"];
    }

那就是我传递的参数代码。

这是我尝试用来填充文本框的形式的代码:

public partial class ChangeSupplier : Form
{
    OleDbConnection dbConn;
    OleDbCommand dbCmd;
    DataSet ds;
    OleDbDataAdapter dbAdapter;
    OleDbDataReader dbReader;

    public ChangeSupplier(OleDbConnection dbConn, OleDbCommand dbCmd, DataSet ds, OleDbDataAdapter dbAdapter)
    {
        InitializeComponent();
        this.dbConn = dbConn;
        this.dbCmd = dbCmd;
        this.ds = ds;
        this.dbAdapter = dbAdapter;
    }

    private void ChangeSupplier_Load(object sender, EventArgs e)
    {
        dgvSuppliers.DataSource = ds.Tables["Suppliers"];
    }

    private void dgvSuppliers_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (dgvSuppliers.SelectedRows.Count > 0)
        {

            dbConn.Open();

            dbCmd = new OleDbCommand("SELECT * FROM Supplier WHERE [Supplier ID] = '" + dgvSuppliers.SelectedRows[0].Cells[0].Value + "'", dbConn);

            dbReader = dbCmd.ExecuteReader();

            while (dbReader.Read())
            {

                txtName.Text = dbReader["[Supplier Name]"].ToString();
                txtTelNo.Text = dbReader["[Telephone No]"].ToString();
                txtAddress.Text = dbReader["[Supplier Address]"].ToString();
                txtContactName.Text = dbReader["[Contact Name]"].ToString();

            }
        }
    }
}

请随时提出任何建议…预先感谢


阅读 383

收藏
2021-04-28

共1个答案

小编典典

这是上述问题的解决方案:

    private void dgvSuppliers_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0)
        {

            DataGridViewRow row = this.dgvSuppliers.Rows[e.RowIndex];

            txtID.Text = row.Cells["Supplier ID"].Value.ToString();
            txtName.Text = row.Cells["Supplier Name"].Value.ToString();
            txtTelNo.Text = row.Cells["Telephone No"].Value.ToString();
            txtAddress.Text = row.Cells["Supplier Address"].Value.ToString();
            txtContactName.Text = row.Cells["Contact Name"].Value.ToString();

        }

    }

我使用行索引来查找用户单击的单元格。

2021-04-28