Editing gridview

  • Thread starter Thread starter Mike P
  • Start date Start date
M

Mike P

I am creating a gridview that can be edited by the user, and one of the
fields to be edited I want to give the user a drop down which is
populated by a db field. This works fine when the current record being
edited already has a value for the dropdown, but there are cases where
the record might not have a value for the dropdown field, which means
that the SelectedValue property causes the app to crash as there is
nothing in the DB table to populate this record.

Here is my code for the field :

<asp:TemplateField HeaderText="Sponsor" SortExpression="Sponsor">
<ItemTemplate>
<asp:Label ID="lblSponsor" Text='<%#
Eval("Sponsor") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlSponsors"
runat="server" DataSourceID="SqlDataSource2"
DataTextField="Sponsor"
DataValueField="Sponsor" SelectedValue="Sponsor" />
</EditItemTemplate>
</asp:TemplateField>

Can anybody help?
 
One way of achieving this is to have "not selected" option, perhaps with a
blank value. The DropDownList allows you to append bound items, so you could
have:

<asp:DropDownList ID="ddlSponsors" runat="server"
DataSourceID="SqlDataSource2"
AppendDtaBoundItems="true"
DataTextField="Sponsor" DataValueField="Sponsor"
SelectedValue="Sponsor">
<asp:ListItem Value="" Text="-- not selected --" />
</asp:DropDownList>

Dave
 
Hi,

Here is a code sample for gridview_rowediting()

protected void gvAmazoneOrders_RowEditing(object sender,
GridViewEditEventArgs e)
{
int index=e.neweditindex;
Dropdownlist sponsers=(DropDownList)
Gridview1.rows[index].findcontrol("ddlSponsors");
//Here check if "sponsers" has the value you want or not.
//like,
for(int i=0;i<sponsers.items.count;i++)
{
if(sponsers.items.value=="xyz")
{
sponsers.selectedvalue=sponsers.items.value;
break;
}
}
}
}

Hope this will help you.

Regards,
Mansi Shah.
 
Back
Top