PDA

View Full Version : Dropdown List in Gridview


phil-c-
10-08-2007, 12:55 PM
Hi guys, I am currently having probelms when I change a selection in a DDL for a row in the gridview (when editing). I am trying to popluate a Textbox, with the DDL selected item.
The error message that I receive is:
"Object reference not set to an instance of an object."

I am using VS 2005, with VB. Here is my code below:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" DataKeyNames="itemnmbr" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" >
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="operid" HeaderText="Auoperid" />
<asp:BoundField DataField="itemnmbr" HeaderText="Item Num" />
<asp:TemplateField HeaderText="Grade ID">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="SqlDataSource2" DataTextField="Grade_ID"
DataValueField="Grade_ID"
AppendDataBoundItems="true"
AutoPostBack="true"
OnDataBound="DropDownList2_DataBound"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" >
<asp:ListItem Value="">Please select a grade</asp:ListItem>
</asp:DropDownList>

<asp:TextBox ID="TextBox3" runat="server"
Text='<%# Bind("grade_id") %>'></asp:TextBox>

</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("grade_id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Qty" HeaderText="Qty" />
<asp:BoundField DataField="Max_Qty" HeaderText="Max Qty" />
</Columns>
</asp:GridView>
<asp:TextBox ID="Grade_TextBox" runat="server"></asp:TextBox>


Code behind:
Protected Sub DropDownList2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ddl As DropDownList
ddl = DirectCast(sender, DropDownList)

Dim row As GridViewRow
row = DirectCast(ddl.NamingContainer, GridViewRow)
row.FindControl("DropDownList2")
'row.Cells(2).FindControl("DropDownList2")

Dim GradeText As TextBox
GradeText = CType(GridView1.FindControl("TextBox3"), TextBox)

GradeText.Text = ddl.SelectedItem.Text
End Sub


Any advice would be much appreciated
Thanks
Phil

nikkiH
10-08-2007, 03:27 PM
I think you'll find that
GridView1.FindControl("TextBox3")
returns null / Nothing

Use the row like you did for the other control.

Also, you should probably Eval the ItemTemplate here, not Bind. Use Bind for EditItemTemplate (as you did).
<asp:Label ID="Label1" runat="server" Text='<%# Bind("grade_id") %>'></asp:Label>