我有一个问题而且我似乎没有在这个问题上做到正确...我一直试图做的是在datagridview单元格中输入一个值(id),按回车键,并使用来自DB(SQL)的数据填充邻接单元格,该数据与我在第一个单元格中输入的id相匹配。问题是:
如何在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;
}
}
}
}
}
}
}
}
答案 0 :(得分:0)
要捕获按键,请尝试以下操作:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var tb =(DataGridViewTextBoxEditingControl)e.Control;
tb.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
e.Control.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
}
private void dataGridViewTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
}
获取当前值:
dataGridView1.CurrentRow.Cell[indexorname].FormattedValue as int
要添加行,请使用DataTable.Merge: