GridView from CodeBehind select row and postback

I need to create GridView100% in C # CodeBehind. I have a row select and record using this code:

    void dataGrid_ItemCreated(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem ||
            e.Item.ItemType == ListItemType.Item)
        {
            e.Item.Attributes.Add("onmouseover",
                   "this.style.backgroundColor='beige';this.style.cursor='pointer'");
            e.Item.Attributes.Add("onmouseout",
                   "this.style.backgroundColor='#FFFFFF';");
            e.Item.Attributes.Add("onclick", "javascript:__doPostBack" +
                   "('_ctl0$DataGrid1$_ctl" +
                   ((Convert.ToInt32(e.Item.ItemIndex.ToString())) + 2) +
                   "$_ctl0','')");
        }
    }

This message is returned, but then how can I get the id of the row that the user clicked on?

+3
source share
2 answers
void dataGrid_ItemCreated(object sender, DataGridItemEventArgs e)
    {
        if(e.Item.ItemType == ListItemType.Item)
        {
            var item = e.Item.DataItem;  // <- entity object that bound, like person
            var itemIndex = e.Item.ItemIndex; // <- index
        }

    }
+1
source

You can pass an argument in the second parameter __doPostBack:

__doPostBack(controlname, yourid);

So fill it out here:

e.Item.Attributes.Add("onclick", "javascript:__doPostBack" +
    "('_ctl0$DataGrid1$_ctl" +
   ((Convert.ToInt32(e.Item.ItemIndex.ToString())) + 2) + 
   "$_ctl0','PUT YOUR VALUE HERE')");

You can then access it through the event arguments.

0
source

All Articles