【发布时间】:2015-02-16 20:52:04
【问题描述】:
我有一个问题,我似乎没有在这个问题中得到正确的答案......我一直在尝试做的是在 datagridview 单元格上输入一个值(id),按下回车键,然后填充相邻的包含来自 DB (SQL) 的数据的单元格,与我在第一个单元格中输入的 id 匹配。问题是:
如何在 datagridview 上获取按键事件?
如何将特定单元格中的值转换为整数?
- 如何将数据表中的行相加,而不删除 datagridview 中的第一行?有更新方法吗?
对不起,如果这些是基本问题,但我似乎找不到答案。 谢谢!
编辑:这是我一直在尝试的代码......我完成的是,当我按下回车键时,除了我已经创建的列之外,我在数据网格上获得了一组新的空列
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCell cell = row.Cells[0];
if (cell.Value == null || cell.Value.Equals("") || cell.ColumnIndex == 0)
{
dataGridView1.CurrentRow.cell[0].FormattedValue as int;
int idArticle = Convert.ToInt32(row.Cells[0].Value);
//int idArticle = Convert.ToInt32(dataGridView1.SelectedCells[0].Value);
dataGridView1.AutoGenerateColumns = true;
string constring = @"Data Source=DAN;Initial Catalog=administration;Integrated Security=True ";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT id_article, article, quantity, precio FROM articlesSG WHERE id_article=@id_article", con))
{
cmd.Parameters.AddWithValue("id_article", idArticle);
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
}
}
}
【问题讨论】:
-
@Grant Winney 谢谢老兄!是的,我认为我在 KeyDown 事件中做对了......我似乎没有做对的事情是将数据从 DB 获取到 datagridview,这本身并不是一件很复杂的事情,但我就是做不到做吧,我想我要出去散散心了。
-
@Grant Winney 好的,当然,我没有粘贴它,因为我只是随机尝试一些东西,它可能没有多大意义......但如果你们,我会试一试有时间,非常感谢您的时间!
-
@Grant Winney 是的,我就是这么想的!很高兴我走在正确的道路上。非常感谢您的建议!如果我设法让它工作,我会稍后发布
标签: c# sql datagridview keypress