列中的文本更改DataGridView在DataBase中搜索并将结果放到其他列

时间:2015-06-24 12:22:06

标签: c# datagridview


我有一个DataGridView和Columns设置manualy
如下所示:
enter image description here


我需要这个:
当BarCode在Column BarCode中输入时,在DataBase中搜索并将Result放入ProductName

我尝试了这个,但它不起作用:

private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    if (Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[0].Value) != "")
    {
        DataTable dtl = new DataTable();
        _id = Int32.Parse(Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells[0].Value));
        dtl = dc.RunQuery(@"SELECT ProductName FROM Product WHERE ProductCode = '" + _id + "'");
        DataRow row = dtl.Rows[0];
        dataGridView1.Rows[e.RowIndex].Cells[1].Value = row[0].ToString();
    }
}

1 个答案:

答案 0 :(得分:1)

你可以尝试CellValueChanged事件来实现你想要的东西,比如,

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    string currentValue = Convert.ToString(dataGridView1.CurrentCell.Value);
    if (e.ColumnIndex == 0 && !string.IsNullOrEmpty(currentValue))
    {
        Int32.TryParse(currentValue, out _id);
        DataTable dtl = dc.RunQuery(@"SELECT ProductName FROM Product WHERE ProductCode = '" + _id + "'");
        DataRow row = dtl.Rows[0];
        dataGridView1.Rows[e.RowIndex].Cells[1].Value = row[0].ToString();
    }
}

希望这会有所帮助......