Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I create a table
T1
--------------------------------------------------
SlNo	       int	        Unchecked
WebsiteName     varchar(100)  	Unchecked
PortId	       varchar(100)	Unchecked
Createdate  	date	        Unchecked

THEN I DESIGN A GRID VIEW AND GET THE VALUE FROM DB LIKE THIS
ASP.NET
<asp:GridView ID="gvDetails" DataKeyNames="SlNo,Websitename" runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand">
<columns><asp:TemplateField><edititemtemplate>
    <asp:Button ID="BtnUpdate" CommandName="Update" runat="server" ToolTip="Update" Height="20px" Width="20px" Text="update" />
<asp:Button ID="BtnCancel" runat="server" CommandName="Cancel"  ToolTip="Cancel" Height="20px" Width="20px" Text="Cancel"/>
</edititemtemplate><itemtemplate>
 <asp:Button ID="BtnUpdate" CommandName="Update" runat="server" ToolTip="Update" Height="20px" Width="20px" Text="update" />
    <asp:Button ID="BtnCancel" runat="server" CommandName="Cancel"  ToolTip="Cancel" Height="20px" Width="20px" Text="Cancel"/>
</itemtemplate><footertemplate>
<asp:Button ID="btnAdd" runat="server"  CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</footertemplate><asp:TemplateField HeaderText="SlNo"><edititemtemplate>
<asp:Label ID="lbleditusr" runat="server" Text=' <%#Container.DataItemIndex+1%> '/>
</edititemtemplate><asp:TemplateField HeaderText="SiteName"><edititemtemplate>
 <asp:LinkButton ID="LinkButton1" runat="server" CommandName="redirect" Text='<%# DataBinder.Eval(Container.DataItem, "WebsiteName")%>'  ToolTip="redirect"></edititemtemplate><itemtemplate>
 <asp:LinkButton ID="LinkButton1" runat="server" CommandName="redirect" Text='<%# DataBinder.Eval(Container.DataItem, "WebsiteName")%>'  ToolTip="redirect"></itemtemplate><footertemplate>
<asp:TextBox ID="txtsitename" runat="server"/>
<asp:RequiredFieldValidator ID="rfvsitename" runat="server" ControlToValidate="txtsitename" Text="*" ValidationGroup="validaiton"/>
</footertemplate></columns>


CODE BEHIND(.CS FILE)
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
public partial class gridview_testing : System.Web.UI.Page
{  
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
            SqlConnection con = new SqlConnection(sqlCon);
            BindEmployeeDetails();
        }
    }
    protected void BindEmployeeDetails()
    {
        string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
        SqlConnection con = new SqlConnection(sqlCon);
        con.Open();
        SqlCommand cmd = new SqlCommand("select WebsiteName from Websitedtls", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        if (ds.Tables[0].Rows.Count > 0)
        {
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
            int columncount = gvDetails.Rows[0].Cells.Count;
            gvDetails.Rows[0].Cells.Clear();
            gvDetails.Rows[0].Cells.Add(new TableCell());
            gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
            gvDetails.Rows[0].Cells[0].Text = "No Records Found";
        }
    }
    protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvDetails.EditIndex = e.NewEditIndex;
        BindEmployeeDetails();
    }
    protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
        SqlConnection con = new SqlConnection(sqlCon);
        int SlNo = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
        string sitename = gvDetails.DataKeys[e.RowIndex].Values["SiteName"].ToString();
        TextBox txtsitename = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtsitename");
        con.Open();
        SqlCommand cmd = new SqlCommand("update Websitedtls set WebsiteName='" + txtsitename + "' where SlNo=" + SlNo, con);
        cmd.ExecuteNonQuery();
        con.Close();
        lblresult.ForeColor = Color.Green;
        lblresult.Text = sitename + " Details Updated successfully";
        gvDetails.EditIndex = -1;
        BindEmployeeDetails();
    }
    protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvDetails.EditIndex = -1;
        BindEmployeeDetails();
    }
    protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
        SqlConnection con = new SqlConnection(sqlCon);
        int SlNo = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["SlNo"].ToString());
        string sitename = gvDetails.DataKeys[e.RowIndex].Values["sitename"].ToString();
        con.Open();
        SqlCommand cmd = new SqlCommand("delete from Websitedtls where SlNo=" + SlNo, con);
        int result = cmd.ExecuteNonQuery();
        con.Close();
        if (result == 1)
        {
            BindEmployeeDetails();
            lblresult.ForeColor = Color.Red;
            lblresult.Text = sitename + " details deleted successfully";
        }
    }
    protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
        SqlConnection con = new SqlConnection(sqlCon);
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtsitename = (TextBox)gvDetails.FooterRow.FindControl("txtsitename");           
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into Websitedtls(WebsiteName) values( '" +txtsitename.Text + "' )", con);
            int result = cmd.ExecuteNonQuery();
            con.Close();
            if (result == 1)
            {
                BindEmployeeDetails();
                lblresult.ForeColor = Color.Green;
                lblresult.Text = txtsitename.Text + " Details inserted successfully";
            }
            else            {
                lblresult.ForeColor = Color.Red;
                lblresult.Text = txtsitename.Text + " Details not inserted";
            }}}}

BUT IT SHOWS ERROR, LIKE THIS
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'SlNo'.
PLS HELP ME TO SOLVE THIS
Posted
Updated 17-Mar-13 22:40pm
v5
Comments
giri001 18-Mar-13 3:12am    
Use the DataKeyNames property to specify the field or fields that represent the primary key of the data source. You must set the DataKeyNames property in order for the automatic update and delete features of the GridView control to work. The values of these key fields are passed to the data source control in order to specify the row to update or delete.
so check once with your database.
jmd :-)

1 solution

As you have set 'DataKeyNames="UserId,UserName"' of your GridView then your source dataset must have the column 'UserId' and 'UserName', The error is becouse you are not retriving UserId, and UserName from database and trying to bind it as the DataKey to the GridView.
 
Share this answer
 
Comments
manjujasmine 18-Mar-13 4:36am    
I do that what u told but still its show the error
vishal.shimpi 18-Mar-13 4:46am    
whats the error... and on which line?
Member 9581488 18-Mar-13 9:53am    
Make one boundfield in your gridview and bind it with your SlNo field, If you do not want user to see that fields you can make it visible="false".
I found out you do not have any itemtemplate or boundfield that actually binds your field to grid.
Hope this hint helps you.

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