I bound the Gridview to the database,Now I want that in each row edit link is there,When i click on dat,then the data of data row comes to edit mode...


SOURCE TAB

<asp:GridView ID="GridView1" runat="server"  onrowediting="GridView1_RowEditing"  AutoGenerateColumns="False">
                        <Columns>
                            <asp:BoundField HeaderText="SNo" DataField ="UID" />
                            <asp:BoundField HeaderText="First Name" DataField ="FirstName" />
                            <asp:BoundField HeaderText="Last Name"  DataField ="LastName" />
                            <asp:BoundField HeaderText="EMail"  DataField ="EMail" />
                            <asp:BoundField HeaderText="Address" DataField ="Address" />
                            <asp:BoundField HeaderText="Phone No"  DataField ="PhoneNo" />
                            <asp:TemplateField > 
                             <ItemTemplate> 
                    <asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" ></asp:LinkButton> 
                </ItemTemplate>
                </asp:TemplateField>
                        </Columns>
                    </asp:GridView>

CODE BEHIND

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Data .SqlClient ; 

public partial class FrmShowData1 : System.Web.UI.Page
{
    string Query;
    SqlCommand cmd;
    SqlConnection conn;
   
   

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                OpenSQLConnection();
                Query = "SELECT * FROM Info1";
                cmd = new SqlCommand(Query, conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill (ds);
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }

        catch (Exception ex)
        {
            Label1.Text = ex.Message.ToString();
        }

    }

    private void OpenSQLConnection()
    {
        try
        {
            conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=Sonia;Integrated Security=true;");
            conn.Open();
        }
        catch (Exception ex)
        {
            Label1 .Text = ex.Message.ToString();
        }

    }
   
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
    }
    
   
}

When i click on the edit link,then firstly page is postbacked,& when i click again,then in current row textboxes come,but i also want the data to come in textboxes of the current cell....Can someebody tell me ,how to have data in textboxes???

Dani AI

Generated

Quick diagnosis: the “click once posts back, click again shows textboxes” behaviour comes from when and how you bind the GridView. In ’s code you set GridView1.EditIndex = e.NewEditIndex in RowEditing, but Page_Load only binds on !IsPostBack. RowEditing runs after Page_Load, so unless you rebind the GridView after setting EditIndex the edit controls won’t be generated until the next request. The fix is to factor your binding into a reusable method and call it after changing EditIndex (and after update/cancel).

Factor binding and rebind in the edit handlers:

private void BindGrid()
{
    string cs = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(cs))
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Info1", conn))
    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
    {
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    BindGrid();
}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    BindGrid();
}

To persist changes (as hinted) implement RowUpdating, use DataKeyNames="UID" on the GridView and either TemplateField EditItemTemplate textboxes (recommended) or read e.NewValues. Example using TemplateField + DataKeys:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
    GridViewRow row = GridView1.Rows[e.RowIndex];
    string first = ((TextBox)row.FindControl("txtFirstName")).Text;
    string last  = ((TextBox)row.FindControl("txtLastName")).Text;

    using (SqlConnection conn = new SqlConnection(connString))
    using (SqlCommand cmd = new SqlCommand("UPDATE Info1 SET FirstName=@FirstName, LastName=@LastName WHERE UID=@UID", conn))
    {
        cmd.Parameters.AddWithValue("@FirstName", first);
        cmd.Parameters.AddWithValue("@LastName", last);
        cmd.Parameters.AddWithValue("@UID", id);
        conn.Open();
        cmd.ExecuteNonQuery();
    }

    GridView1.EditIndex = -1;
    BindGrid();
}

Extra tips: put the connection string in web.config, always use parameterized queries, wire OnRowUpdating/OnRowCancelingEdit in markup (or event handlers), and prefer TemplateFields for predictable control IDs when reading edited values.

If you want to edit data in gridview why are you not using the update command???

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.