Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello, i cant edit-update in grid view when i execute this code and press edit button the error occurly coime like:-
SQL
'cmbType' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value


pls suggest me wht should i do for this pls suggest me to solve this problem

thank you
XML
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:customerConnectionString %>"
            SelectCommand="SELECT [id], [name], [gender], [city], [state] FROM [cust_info]">
        </asp:SqlDataSource>
        <asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing">
<Columns>
 <asp:TemplateField HeaderText="ID" Visible="False">
   <ItemTemplate>
    <asp:Label ID="lblid" runat="server" Text='<%# Eval("id")%>'></asp:Label>
         </ItemTemplate>
    </asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<EditItemTemplate>
  <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewName" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Gender">
<EditItemTemplate>
  <asp:DropDownList ID="cmbGender" runat="server"  DataTextField="Gender" DataValueField="Gender" >  </asp:DropDownList>
  <asp:TextBox ID="txtgndr" runat="server" Text='<%# Eval("gender") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="lbGender" runat="server" Text='<%# Eval("gender") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewGender" runat="server"  DataTextField="Gender" DataValueField="Gender"> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="City">
<EditItemTemplate>
  <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewCity" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label3" runat="server" Text='<%# Bind("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="State" SortExpression="State">
<EditItemTemplate>
  <asp:Label ID="Label1" runat="server" Text='<%# Eval("state") %>'></asp:Label>

</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewState" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label4" runat="server" Text='<%# Bind("state") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Type">
<EditItemTemplate>
  <asp:DropDownList ID="cmbType" runat="server" DataTextField="Type" DataValueField="Type" SelectedValue='<%# Eval("type") %>'> </asp:DropDownList>

</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="Label5" runat="server" Text='<%# Eval("type") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList>

</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />

</Columns>
</asp:GridView>
    </div>
    </form>
</body>
</html>



C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["customerConnectionString"].ToString());

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadGridView();
        }
    }

    private void LoadGridView()
    {
        SqlDataAdapter adap = new SqlDataAdapter("select * from cust_info", conn);
        DataSet ds = new DataSet();
        adap.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "AddNew")
        {
            string name = (GridView1.FooterRow.FindControl("txtNewName") as TextBox).Text;
            string gender = (GridView1.FooterRow.FindControl("cmbNewGender") as DropDownList).Text;
            string city = (GridView1.FooterRow.FindControl("txtNewCity") as TextBox).Text;
            string state = (GridView1.FooterRow.FindControl("txtNewState") as TextBox).Text;
            string type = (GridView1.FooterRow.FindControl("cmbNewType") as DropDownList).Text;

            SqlCommand comm = new SqlCommand();
            comm.CommandText = "insert into cust_info (name,gender,city,state,type) values(@name,@gender,@city,@state,@type)";
            comm.Connection = conn;

            comm.Parameters.AddWithValue("@name", name.ToString());
            comm.Parameters.AddWithValue("@gender", gender.ToString());
            comm.Parameters.AddWithValue("@city", city.ToString());
            comm.Parameters.AddWithValue("@state", state.ToString());
            comm.Parameters.AddWithValue("@type", type.ToString());

            conn.Open();
            comm.ExecuteNonQuery();
            conn.Close();

            LoadGridView();

        }
    }

    public DataTable FetchCustomerType()
    {
        string sql = "Select Distinct type From cust_info";
        SqlDataAdapter da = new SqlDataAdapter(sql, conn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }

    public DataTable FetchCustomerGender()
    {
        string sql = "Select Distinct gender From cust_info";
        SqlDataAdapter da = new SqlDataAdapter(sql, conn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList cmbtype = (DropDownList)e.Row.FindControl("cmbType");
            DropDownList cmbgnder = (DropDownList)e.Row.FindControl("cmbGender");
            if (cmbtype != null && cmbgnder != null)
            {

                cmbgnder.DataSource = FetchCustomerGender();
                cmbgnder.DataBind();
                cmbgnder.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[2].ToString();
                cmbtype.DataSource = FetchCustomerType();
                cmbtype.DataBind();
                cmbtype.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

            }
        }



        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList cmbnewtype = (DropDownList)e.Row.FindControl("cmbNewType");
            DropDownList cmbnewgnder = (DropDownList)e.Row.FindControl("cmbNewGender");
            cmbnewgnder.DataSource = FetchCustomerGender();
            cmbnewgnder.DataBind();
            cmbnewtype.DataSource = FetchCustomerType();
            cmbnewtype.DataBind();


        }
        
        
            
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;

        string id = (row.FindControl("lblID") as Label).Text;
        string name = (row.FindControl("txtName") as TextBox).Text;
        string gender = (row.FindControl("cmbGender") as DropDownList).Text;
        string city = (row.FindControl("txtCity") as TextBox).Text;
        string state = (row.FindControl("txtstate") as TextBox).Text;
        string type = (row.FindControl("cmbType") as DropDownList).Text;

        SqlCommand comm = new SqlCommand();
        comm.CommandText = "update cust_info set name=@name,city=@city,state=@state where id=@id";
        comm.Connection = conn;

        comm.Parameters.AddWithValue("@name", name.ToString());
        comm.Parameters.AddWithValue("@id", id.ToString());
        comm.Parameters.AddWithValue("@gender", gender.ToString());
        comm.Parameters.AddWithValue("@city", city.ToString());
        comm.Parameters.AddWithValue("@state", state.ToString());
        comm.Parameters.AddWithValue("@type", type.ToString());

        conn.Open();
        comm.ExecuteNonQuery();
        conn.Close();

        GridView1.EditIndex = -1;
        LoadGridView();

    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        LoadGridView();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        LoadGridView();
    }
}
Posted
Updated 1-Mar-12 23:16pm
v2
Comments
Anuja Pawar Indore 2-Mar-12 5:17am    
Added code block
dimpledevani 2-Mar-12 5:18am    
well try using cmbtype.SelectedItem.Text to match display member or cmbtype.SelectedItem.Value for value member in your code
djharry2 2-Mar-12 5:27am    
whr should i put tht snippts which u say " cmbtype.SelectedItem.Text to match display member or cmbtype.SelectedItem.Value"

1 solution

Seems you are using DataKeys property in the following lines of codes.

C#
cmbgnder.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[2].ToString();
 cmbtype.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();



But to use DataKey you need to specify DataKeyNames property in GridView. I do not see you did it anywhere.

Add DataKeyNames to your gridview as follows:

DataKeyNames="Type,Gender" - You can comma separate more than one key.

ASP.NET
<asp:gridview id="GridView1" runat="server" showfooter="true" autogeneratecolumns="False" onrowcommand="GridView1_RowCommand" onrowdatabound="GridView1_RowDataBound" onrowupdating="GridView1_RowUpdating" onrowcancelingedit="GridView1_RowCancelingEdit" onrowediting="GridView1_RowEditing" xmlns:asp="#unknown"><asp:gridview id="GridView1" runat="server" showfooter="true" autogeneratecolumns="False" onrowcommand="GridView1_RowCommand" onrowdatabound="GridView1_RowDataBound" onrowupdating="GridView1_RowUpdating" onrowcancelingedit="GridView1_RowCancelingEdit" onrowediting="GridView1_RowEditing">
DataKeyNames="Type,Gender"></asp:gridview></asp:gridview>


Please let me know if it helps by giving rate to the answer.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900