This is a migrated thread and some comments may be shown as answers.

DataKeyValue on Button click

3 Answers 284 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Jagat
Top achievements
Rank 1
Jagat asked on 02 Oct 2012, 06:06 PM
I have a button in one of the columns of the RadGrid. How to get the DataKeyValue of that row when the button is clicked on the client-side.
 Currentyl I am using the 'SelectedIndex' routine on the server-side but since the index changes continously as more data is being added to the backend database by other users of the application this creates an issue leading to the user ending up editing a wrong record?

3 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 03 Oct 2012, 05:08 AM
Hi Jagat,

You can get the datakeyvalue using the following approaches.

1)From server side:
C#:
protected void Button1_Click1(object sender, EventArgs e)
{
     Button btn = (Button)sender;
     GridDataItem item = (GridDataItem)btn.NamingContainer;
     string key = item.GetDataKeyValue("ID").ToString();
}

2)From client side:
JS:
function OnClientClick() {
    var masterTable = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
    var row = masterTable.get_dataItems();
    for (var i = 0; i < row.length; i++)
     {
       alert(masterTable.get_dataItems()[i].getDataKeyValue("ID"));
     }
    }

Thanks,
Shinu.
0
Jagat
Top achievements
Rank 1
answered on 03 Oct 2012, 02:35 PM
Hi Shinu,

Thanks, but I need the ID of the row on which the button was clicked (Client-side code). Here you are looping through all the rows...How do you get the index of that particular row in which the button was clicked?
0
Shinu
Top achievements
Rank 2
answered on 04 Oct 2012, 03:59 AM
Hi Jagat,

Please try the following code snippet to get the DataKeyValue in client side.

ASPX:
<telerik:RadGrid . . . . . .>
  <MasterTableView DataKeyNames="OrderID" ClientDataKeyNames="OrderID">

C#:
protected void LookupRadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
       GridDataItem item = (GridDataItem)e.Item;
       Button lb = (Button)item.FindControl("Button1");
       lb.Attributes.Add("onclick", "onClientClick('" + item.ItemIndex + "');");
    }
}

Javascript:
<script type="text/javascript">
   function onClientClick(index)
   {
      var grid = $find("<%=RadGrid1.ClientID %>");
      var MasterTable = grid.get_masterTableView();
      var row = MasterTable.get_dataItems()[index];
      var Id = row.getDataKeyValue("OrderID") //access DataKeyValue
      alert(Id);
   
</script>

Thanks,
Shinu.
Tags
Grid
Asked by
Jagat
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Jagat
Top achievements
Rank 1
Share this question
or