Editing gridview

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?
 
D

Dave Sussman

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
 
M

Mansi Shah

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top