如何以编程方式选择DataGridView中的行并触发DataGridView.SelectionChanged事件?

时间:2016-09-21 18:02:05

标签: c# datagridview

对于我的生活,我似乎无法弄清楚这一点。我有一个很长的DataGridView(不允许MultiSelect),当用户提交数据更改时,网格中的数据被清除并重新绘制(因为更改可能影响多行,这是更简单的方法)。但是,当我尝试以编程方式选择行时,它也不会触发DataGridView.SelectionChanged事件,我用它来显示与DataGridView当前单元格索引相关的数组中的数据。当doMagicStuff执行时,将显示错误索引(特别是索引0)的值。

private void doMagicStuff()
{
    int selRow = myDGV.CurrentCell.RowIndex;
    myDGV.Rows.Clear();

    /*Perform Task, Redraw data*/
    myDGV.CurrentCell = myDGV[selRow, 0];
}
private void myDGV_SelectionChanged(object sender, EventArgs e)
{
    Label1.Text = myDisplayValue1[myDGV.CurrentCell.RowIndex];
    Label2.Text = myDisplayValue2[myDGV.CurrentCell.RowIndex];
    TextBox1.Text = myEditValue1[myDGV.CurrentCell.RowIndex];
    TextBox2.Text = myEditValue2[myDGV.CurrentCell.RowIndex];
}

2 个答案:

答案 0 :(得分:0)

确保您的客户端设置和OnSelectedIndexChanged设置如下:(ASP.NET AJAX)

.aspx page

<telerik:RadGrid ID="Grid1" runat="server" OnSelectedIndexChanged="Grid1_SelectedIndexChanged" OnItemDataBound="Grid1_ItemDataBound" OnPreRender="Grid1_PreRender">
             <ClientSettings EnablePostBackOnRowClick="true">
                      <Selecting AllowRowSelect="true"></Selecting>
             </ClientSettings>
</telerik:RadGrid>


aspx.cs页面

protected void Grid1_SelectedIndexChanged(object sender, EventArgs e)
    {

        string value = null;
        foreach(GridDataItem item in Grid1.SelectedItems)
        {
            //column name is in doub quotes
            value = item["Name"].Text;
        }
    }

答案 1 :(得分:0)

单击一个按钮单击表单以测试DataGridView中的选定值。双击该按钮,然后将此代码粘贴到那里

foreach (DataGridViewRow row in myDGV.SelectedRows)
{
    Label1.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values 
    Label2.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values 
    TextBox1.Text = row.Cells[0].Value.ToString();//change the 0 or 1 to fit your column Index position 
    TextBox2.Text = row.Cells[2].Value.ToString();  
}

如果你有4列和4个文本框,那么你将在foreach循环中分配所有textbox.Text值,只需遵循模式并将索引增加1,因此2个文本框意味着row.Cells [0]是第一列row.Cells [1]是第二列...... etc