datagridview keypress 事件为何选中最后一条记录
模糊查询到数据加载到datagridview 中,想用keypress事件选中行的记录并放到相应的容器中,但有很多记录时选中的是最后一行数据,请大家赐教.datagridview 加载时代码:
private void txt_byName_KeyPress(object sender, KeyPressEventArgs e)
{
//if (e.KeyChar == 13)
//{
string sql = "select a.CP_id,a.CP_name,a.CP_xh,a.CP_sbh,a.CP_dw,a.CP_jj,a.CP_SJ,a.JH_SL,a.GHS_id,a.BZ,b.CP_byName " +
"from LZ_ZKCB a ,CLinfo b where a.CP_id=b.CP_id and b.CP_byName like '%" + txt_byName.Text + "%'";
my_ds = new DataSet();
my_ds = my_Service.RunProca(sql, my_ds);
//if (my_ds.Tables[0].Rows.Count > 1)
//{
dataGridView1.Visible = true;
dataGridView1.Focus();
my_tb = new DataTable();
my_tb = my_ds.Tables[0];
my_tb.Columns.Add("序号");
int iCount = 0;
foreach (DataRow row in my_tb.Rows)
{
iCount += 1;
row.BeginEdit();
row["序号"] = iCount.ToString();
row.EndEdit();
}
my_tb.DefaultView.AllowDelete = true;
my_tb.DefaultView.AllowEdit = true;
my_tb.DefaultView.AllowNew = false;
this.dataGridView1.DataSource = my_tb.DefaultView;
//dataGridView1.Rows[0].Selected = true;
//}
//else
//{
// foreach (DataRow arow in my_ds.Tables[0].Rows)
// {
// txt_byName.Text = arow["CP_byName"].ToString();
// txt_BZ.Text = arow["BZ"].ToString();
// txt_id.Text = arow["CP_id"].ToString();
// txt_JJ.Text = arow["CP_jj"].ToString();
// txt_Name.Text = arow["CP_name"].ToString();
// txt_SBH.Text = arow["CP_sbh"].ToString();
// txt_SJ.Text = arow["CP_SJ"].ToString();
// txt_XH.Text = arow["CP_xh"].ToString();
// txt_SL.Text = arow["JH_SL"].ToString();
// cob_DW.Text = arow["CP_dw"].ToString();
// cob_GHS.Text = arow["GHS_id"].ToString();
// }
//}
//}
}
以下是KeyPress事件代码:
private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
//if (e.KeyChar == 13)
//{
foreach (DataGridViewRow arow in this.dataGridView1.SelectedRows)
{
txt_byName.Text = arow.Cells["CP_byName"].Value.ToString();
txt_BZ.Text = arow.Cells["BZ"].Value.ToString();
txt_id.Text = arow.Cells["CP_id"].Value.ToString();
txt_JJ.Text = arow.Cells["CP_jj"].Value.ToString();
txt_Name.Text = arow.Cells["CP_name"].Value.ToString();
txt_SBH.Text = arow.Cells["CP_sbh"].Value.ToString();
txt_SJ.Text = arow.Cells["CP_SJ"].Value.ToString();
txt_XH.Text = arow.Cells["CP_xh"].Value.ToString();
txt_SL.Text = arow.Cells["JH_SL"].Value.ToString();
cob_DW.Text = arow.Cells["CP_dw"].Value.ToString();
cob_GHS.Text = arow.Cells["GHS_id"].Value.ToString();
dataGridView1.Visible = false;
}
//}
} --------------------编程问答-------------------- 这不废话..
如果选中有2行,你循环这2行
然后往控件赋值
那你的第2行肯定覆盖了1行的值啊
你有多少行就应该拿多少个容器来存放这些值!
--------------------编程问答-------------------- dataGridView1.SelectedRows dataGridView1里面只能有一行被选中.
补充:.NET技术 , C#