This question already has an answer here:
这个问题在这里已有答案:
- How to get values from template fields in GridView? 6 answers
- What is a NullReferenceException, and how do I fix it? 33 answers
如何从GridView中的模板字段中获取值? 6个答案
什么是NullReferenceException,我该如何解决? 33个答案
I have a DropDownList which is shown below:
我有一个DropDownList,如下所示:
<asp:GridView ID="moduleInfo" runat="server" DataSourceID="currentModules" class="table table-striped table-bordered" AutoGenerateColumns="false" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="module" ItemStyle-Width="30" >
<ItemTemplate>
<asp:DropDownList ID="entryLevel" CssClass="form-control" runat="server">
<asp:ListItem Text="Level 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Level 2" Value="2"></asp:ListItem>
<asp:ListItem Text="Level 3" Value="3"></asp:ListItem>
<asp:ListItem Text="Level 4" Value="4"></asp:ListItem>
<asp:ListItem Text="Level 5" Value="5"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
When I try to reference it in the code behind it was not recognized by typing entryLevel
, so i used below code:
当我尝试在后面的代码中引用它时,通过输入entryLevel无法识别,所以我使用下面的代码:
DropDownList ddl = (DropDownList)moduleInfo.FindControl("entryLevel");
string Level = ddl.SelectedValue;
Whenever I run the web-page and select the value, I get the error:
每当我运行网页并选择值时,我都会收到错误:
object reference not set to an instance of an object
你调用的对象是空的
Anyone know why I'm getting this error?
任何人都知道我为什么会收到这个错误?
1 个解决方案
#1
0
You are missing Rows
class of GridView to get the exact DropDownList replace below line:
你缺少GridView的Rows类来获得下面一行的确切DropDownList替换:
DropDownList ddl = (DropDownList)moduleInfo.Rows[rowIndex].FindControl("entryLevel");
And if you are using your code in RowCommand event then you can get rowIndex
as like this:
如果您在RowCommand事件中使用您的代码,那么您可以像这样获取rowIndex:
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int rowIndex = row.RowIndex;
#1
0
You are missing Rows
class of GridView to get the exact DropDownList replace below line:
你缺少GridView的Rows类来获得下面一行的确切DropDownList替换:
DropDownList ddl = (DropDownList)moduleInfo.Rows[rowIndex].FindControl("entryLevel");
And if you are using your code in RowCommand event then you can get rowIndex
as like this:
如果您在RowCommand事件中使用您的代码,那么您可以像这样获取rowIndex:
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int rowIndex = row.RowIndex;