我有一个网格视图,需要从ASP.NET/C#中的事件ondatabinding访问该行的datakeyname。我如何从ondatabindings访问数据键?这甚至可以由三个不同网格视图中的一个调用。我该如何从ondatabinding中获取这些行的datakeyname?
ondatabinding="PreventErrorOnbinding"
DataKeyNames="ID"
<asp:TemplateField HeaderText="Purpose" SortExpression="Purpose" ItemStyle-Width="50px" HeaderStyle-Width="50px" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:Label ID="LabelPurpose" runat="server" Text='<%# Eval("Purpose") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddPurpose1" ondatabinding="PreventErrorOnbinding" class="txtSize" SelectedValue='<%# Bind("Purpose") %>' AppendDataBoundItems="true" runat="server">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="ddPurposeRequiredFieldValidator1" runat="server" Display="Dynamic" ForeColor="Red"
ErrorMessage="Select a purpose type." InitialValue="" ControlToValidate="ddPurpose1" ValidationGroup="relationshipGroup2" />
</EditItemTemplate>
C#:
protected void PreventErrorOnbinding(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ddl.DataBinding -= new EventHandler(PreventErrorOnbinding);
ddl.AppendDataBoundItems = true;
ListItem li = new ListItem("Select a purpose type.", "");
ddl.Items.Insert(0, li);
//Get this purpose from the db and insert it into the list and then add the other default items also.
//This will allow us to edit items that do not exist within the list that were set before this was a dropdown list when it was a textbox.
try
{
ddl.DataBind();
}
catch (ArgumentOutOfRangeException)
{
GridViewRow row = (GridViewRow)ddl.NamingContainer;
//int index = GetColumnIndexByName(row, "ID");
//Int64 columnValue = Convert.ToInt64(row.Cells[index].Text.Trim());
//similar to this but the gridview would need to be accessed dynamically.
// var id = gvTransactionHistory.DataKeys[rowIndex].Values["ID"];
int RowIndex = row.RowIndex;
//Int64 rowID = Convert.ToInt64(????.DataKeys[RowIndex].Values["ID"].ToString().Trim());
//ddl.SelectedValue = Globals.GetDropDownValue(rowID);
//get item from the db for this contact
//append the rest
ddl.Items.Clear();
ddl.DataSourceID = ddPurposeSqlDataSource.ID;
ddl.DataBind();
}
}
明白了!
GridViewRow row = (GridViewRow)ddl.NamingContainer;
DataRow dr = ((DataRowView)row.DataItem).Row;
string id = dr["ID"].ToString().Trim();
string id2 = ((System.Data.DataRowView)(row.DataItem)).Row["ID"].ToString().Trim();