I am trying to implement the code from Mr. Mudassar:
http://www.aspsnippets.com/Articles/Populate-DropDownList-with-Selected-Value-in-EditItemTemplate-of-GridView-in-ASPNet.aspx
I have a database table with Integer type.
Here is the running code line:
Code in GridView:
<asp:TemplateField HeaderText="RegionNavn">
<ItemTemplate>
<%# Eval("RegionNavn")%>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblRegionNavn" runat="server" Text='<%# Eval("RegionNavn")%>' Visible = "false"></asp:Label>
<asp:DropDownList ID="dropDownRegionNavn" runat="server" Width="150px" AutoPostBack="true">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
Code in Method GridView_UpdateRecord:
DropDownList ddRegionID = (DropDownList)row.FindControl("dropDownRegionNavn");
dCmd.Parameters.Add("@RegionID", SqlDbType.Int).Value = int.Parse(ddRegionID.SelectedValue);
---------------------------------------------------------------------------------
Code in Method GridView_RowDataBound:
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
DropDownList ddlRegionNavn = (DropDownList)e.Row.FindControl("dropDownRegionNavn");
string query = "select distinct RegionNavn from kart_Region";
SqlCommand cmd = new SqlCommand(query);
ddlRegionNavn.DataSource = GetData(cmd);
ddlRegionNavn.DataTextField = "RegionNavn";
ddlRegionNavn.DataValueField = "RegionNavn";
ddlRegionNavn.DataBind();
ddlRegionNavn.Items.FindByValue((e.Row.FindControl("lblRegionNavn") as Label).Text).Selected = true;
-----------------------------------------
On Edit Click, the DropDownList in the GridView brings the previously selected value
On Update Click, the error is: "System.FormatException: Input string was not in a correct format."
dCmd.Parameters.Add("@KystverketRegionID", SqlDbType.Int).Value = int.Parse(ddKystverketRegionID.SelectedValue);
When I use the following code:
ddlRegionNavn.DataTextField = "RegionNavn";
ddlRegionNavn.DataValueField = "RegionID"; // from RegionNavn to RegionID
On Edit Click, the DropDownList values in the GridView is not firing and the following error shows:
Object reference not set to an instance of an object.
How to implement the code from Mr. Mudassar when having a value of type Int ?
Any Suggestions will be highly appreciated?