11
<telerik:RadGrid ID="radGrid" runat="server" AllowPaging="true" AllowCustomPaging="True"
    GridLines="None" PageSize="20" AllowMultiRowSelection="true" ClientSettings-Selecting-AllowRowSelect="true"
    AutoGenerateColumns="false" onneeddatasource="radGrid_NeedDataSource" OnItemCreated="radGrid_ItemCreated"
    OnItemDataBound="radGrid_ItemDataBound" OnItemCommand="radGrid_ItemCommand"
    DataKeyNames="ClientID">
    <mastertableview datakeynames="ID" gridlines="None" width="100%">
    <PagerTemplate> and so on ... </telerik:RadGrid>

场景: -上面给出的是我正在使用的 Telerik RagGrid 控件的标记。我尝试以通常的方式访问 GridColumn 的 KeyValue,

Int32 key = Convert.ToInt32((e.Item as GridDataItem).GetDataKeyValue("ID"));

这是行不通的。有替代品吗?

4

4 回答 4

20

请尝试以下代码片段。

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{

    if (e.Item is GridDataItem)
    {
        // NORMAL MODE
        GridDataItem item = e.Item as GridDataItem;
        string strId = item.GetDataKeyValue("ID").ToString();
    }

    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {

        if (e.Item is GridEditFormInsertItem)
        {
            // INSERT MODE
            GridEditableItem editedItem = e.Item as GridEditableItem;

        }
        else
        {
            // EDIT MODE
            GridEditableItem editedItem = e.Item as GridEditableItem;
            string strId = editedItem.GetDataKeyValue("ID").ToString();

        }

    }
}


protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
    if (e.CommandName == "YourCommandName")
    {
        GridDataItem item = e.Item as GridDataItem;
        string strId = item.GetDataKeyValue("ID").ToString();
    }
}
于 2012-10-12T13:53:03.730 回答
4

试试这个

string keyValue = radGrid.MasterTableView.DataKeyValues[e.item.ItemIndex].ToString();
int key = Convert.ToInt32(keyValue);
于 2012-10-12T13:12:00.300 回答
2

在标记中定义您的数据键:

< MasterTableView datakeynames="ID" dir="RTL">< /MasterTableView>

并在后面的代码中访问:

GridDataItem item = (GridDataItem)e.Item;

var key = item.GetDataKeyValue("ID");
于 2013-10-27T09:10:32.277 回答
0

您正在尝试访问甚至未在 radgrid 标记中指定的数据键:

DataKeyNames="ClientID"

Int32 key = Convert.ToInt32(dataItem.GetDataKeyValue("ID"));

它应该是:

Int32 key = Convert.ToInt32(dataItem.GetDataKeyValue("ClientID"));
于 2012-10-12T14:40:52.203 回答