vb.net ASP.NET GridView_RowEditing 获取单元格的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16742984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET GridView_RowEditing get value of cell
提问by user1599309
This is pretty basic stuff, but I am unable to extract the text from a cell in my gridview.
这是非常基本的东西,但我无法从网格视图中的单元格中提取文本。
<asp:TemplateField HeaderText="Rolle" SortExpression="role">
<ItemTemplate>
<asp:Label ID="roleLabel" runat="server" Text='<%# Eval("role") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList style="width: 200px;" ID="roleDropdown" runat="server" DataSourceID="SqlDataSourceDropDownlist" DataTextField="role" DataValueField="roleID"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
?
?
Protected Sub GridView1_rowediting(sender As Object, e As GridViewEditEventArgs) Handles GridView1.RowEditing
Dim tb As Label
tb = CType(GridView1.SelectedRow.Cells(1).FindControl("roleLabel"), Label)
Dim userRoleString As String = tb.Text
End Sub
I received this error:
我收到此错误:
Object reference not set to an instance of an object.
How do i extract the text from the cell in a GridView?
如何从 GridView 中的单元格中提取文本?
采纳答案by fnostro
Most likely you need to find the control you want first then grab the text, something like this:
很可能您需要先找到所需的控件,然后抓取文本,如下所示:
Dim tb as TextBox
tb = CType(GridView1.SelectedRow.Cells(1).FindControl("ID_Of_Some_textbox"), TextBox)
Dim userRoleString As String = tb.Text
EDIT: Added Sample code
编辑:添加示例代码
The basic Idea:
基本理念:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="user_id"
DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField HeaderText="user_name" SortExpression="user_name">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="user_name"
DataValueField="user_name" SelectedValue='<%# Bind("user_name") %>' >
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("user_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
回答by user3144884
Do something like this in RowDataBound
在 RowDataBound 中做这样的事情
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int index = 0;
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
DropDownList dl = (DropDownList)e.Row.FindControl("ddlDriverID1");
foreach (ListItem li in dl.Items)
{
if (li.Text == ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[19].ToString())
{
dl.SelectedIndex = index;
break;
}
index += 1;
}
}
}

