[Solved] ASP.Net GridView row Edit Button Click display only first row details

Last Reply one month ago By pandeyism

Posted one month ago

i have used button control in gridview to edit gridview but its only works for the first row

edit button didnt work for other rows.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" ValidateRequest="false" CodeBehind="addplant.aspx.cs" Inherits="Green_Garden.WebForm18" %>

<%--<%@ Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>--%>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
   
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:GridView ID="GridView2" DataKeyNames="p_id"  AutoGenerateColumns="false" Class="table table-hover table-condensed" GridLines="None" runat="server">
        <Columns>
            <asp:TemplateField HeaderText="pid" ItemStyle-Width="50px" HeaderStyle-BackColor="Black" HeaderStyle-ForeColor="White">
                <ItemTemplate>
                    <asp:Label ID="pid" runat="server" Text='<%#Eval("p_id") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Plant Name" ItemStyle-Width="50px" HeaderStyle-BackColor="Black" HeaderStyle-ForeColor="White">
                <ItemTemplate>
                    <asp:Label ID="pname" runat="server" Text='<%#Eval("p_name") %>'></asp:Label>


                </ItemTemplate>
            </asp:TemplateField >
            <asp:TemplateField  HeaderText=" Image" ItemStyle-Width="70px" HeaderStyle-BackColor="Black" HeaderStyle-ForeColor="White">
                <ItemTemplate>
                    <asp:Image ID="Image1" Width="150px" Height="150px" DataImageUrlField="image" ImageUrl='<%#Eval ("image") %>' runat="server" />

                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField  HeaderText=" Category id" ItemStyle-Width="50px" HeaderStyle-BackColor="Black" HeaderStyle-ForeColor="White">
                <ItemTemplate>
                   <asp:Label ID="ct" runat="server" Text='<%#Eval("cat_id") %>'></asp:Label>

                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Quantity" ItemStyle-Width="60px" HeaderStyle-BackColor="Black" HeaderStyle-ForeColor="White">
                <ItemTemplate>
                    <asp:Label ID="qty" runat="server" Text='<%#Eval("qty") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Price"  ItemStyle-Width="70px" HeaderStyle-BackColor="Black" HeaderStyle-ForeColor="White">
                <ItemTemplate>
                    <asp:Label ID="price" runat="server" Text='<%#Eval("price") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>            
            <asp:TemplateField  HeaderText="Description" HeaderStyle-BackColor="Black" HeaderStyle-ForeColor="White">
                <ItemTemplate>                   
                    <asp:Label ID="des"  runat="server" Text='<%#Eval("descp") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Action" ItemStyle-Width="150px" HeaderStyle-BackColor="Black" HeaderStyle-ForeColor="White">
                <ItemTemplate>                        
                             <a href="?id=<%#Eval("p_id") %>">
                    <asp:Button ID="btnEdit" runat="server"   Text="Edit" OnClick="btnEdit_Click" CssClass="btn btn-primary" />
                    </a>                                 
                    <asp:Button ID="btndelete" runat="server" OnClientClick="return confirm('Are you sure you want to delete this?');" Text="Delete" OnClick="btndelete_Click" CssClass="btn btn-danger" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</asp:Content> 
namespace Green_Garden
{
    public partial class WebForm18 : System.Web.UI.Page
    {
        protected void btnEdit_Click(object sender, EventArgs e)
        {
                    submit.Visible = false;
                    btnUpdate.Visible = true;
                    string lbl = ((Label)GridView2.Rows[0].Cells[0].FindControl("pid")).Text;
   
                    SqlCommand cmd2 = new SqlCommand();
                    cmd2.Connection = con;
                    con.Open();
                    cmd2.CommandType = CommandType.Text;
                    cmd2.CommandText = "select * from plants where p_id=@Id";
                    cmd2.Parameters.AddWithValue("@Id", lbl);

                    SqlDataReader dr = cmd2.ExecuteReader();
                    if (dr.HasRows)
                    {

                        while (dr.Read())
                        {

                            pname.Text = dr["p_name"].ToString();
                            Image2.ImageUrl = dr["Image"].ToString();
                            imagelink = dr["Image"].ToString();
                            Image2.ImageUrl = imagelink + "?n=" + DateTime.Now.Second.ToString();
                            qty.Text = dr["qty"].ToString();
                            price.Text = dr["price"].ToString();
                            desc.Text = dr["descp"].ToString();


                        }
                    }
                    dr.Close();
                    con.Close();
                }
        }
}        
You are viewing reply posted by: pandeyism one month ago.
Posted one month ago

Hi fkz2899,

Refer below sample.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function ShowImagePreview(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#<%=Image2.ClientID%>').prop('src', e.target.result).width(50).height(50);
                };
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div class="container">
            <div class="row ">
                <div class="table-responsive ">
                    <div class="col-sm-10 well" style="border-bottom-right-radius">
                        <hr />
                        <div class="form-inline">
                            <div class="form-group">
                                <label for="date">
                                    Name:</label>
                                <asp:TextBox ID="pname" class="form-control" ValidationGroup="validate" Style="width: 150px"
                                    runat="server"></asp:TextBox>
                            </div>
                        </div>
                        <br />
                        <div class="form-inline">
                            <div class="form-group">
                                <label for="image">
                                    Image</label>
                                <asp:Image ID="Image2" runat="server" Width="50px" Height="50px" />
                                <asp:FileUpload onchange="ShowImagePreview(this);" ID="f1" runat="server" Width="172px" />
                            </div>
                        </div>
                        <br />
                        <asp:Label ID="Label3" runat="server" Text="" Visible="false"></asp:Label>
                        <asp:Button class="btn btn-success text-center" ID="submit" runat="server" ValidationGroup="validate"
                            Text="Submit" OnClick="submit_Click" />
                        <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click"
                            Visible="false" CssClass="btn btn-info" Font-Bold="true" />
                        <asp:Button ID="btnClear" runat="server" Text="Clear" OnClick="btnClear_Click" CssClass="btn btn-warning"
                            Font-Bold="true" />
                    </div>
                </div>
            </div>
        </div>
        <hr />
        <asp:GridView ID="GridView2" DataKeyNames="Id" AutoGenerateColumns="false" Class="table table-hover table-condensed"
            GridLines="None" runat="server">
            <Columns>
                <asp:TemplateField HeaderText="Id" ItemStyle-Width="50px" HeaderStyle-BackColor="Black"
                    HeaderStyle-ForeColor="White">
                    <ItemTemplate>
                        <asp:Label ID="pid" runat="server" Text='<%#Eval("Id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name" ItemStyle-Width="50px" HeaderStyle-BackColor="Black"
                    HeaderStyle-ForeColor="White">
                    <ItemTemplate>
                        <asp:Label ID="pname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText=" Image" ItemStyle-Width="70px" HeaderStyle-BackColor="Black"
                    HeaderStyle-ForeColor="White">
                    <ItemTemplate>
                        <asp:Image ID="Image1" Width="50px" Height="50px" DataImageUrlField="image" ImageUrl='<%#Eval ("Path") %>'
                            runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Action" ItemStyle-Width="150px" HeaderStyle-BackColor="Black"
                    HeaderStyle-ForeColor="White">
                    <ItemTemplate>
                        <a href="?id=<%#Eval("Id") %>">
                            <asp:Button ID="btnEdit" runat="server" Text="Edit" OnClick="btnEdit_Click" CssClass="btn btn-primary" />
                        </a>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Namespaces

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

VB.Net

Imports System.Data.SqlClient
Imports System.Data
Imports System.IO

Code

C#

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

private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM tblFilespath", con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                da.Fill(dt);
                GridView2.DataSource = dt;
                GridView2.DataBind();
            }
        }
    }
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
    if (f1.HasFile == true)
    {
        string str = f1.FileName;
        f1.PostedFile.SaveAs(Server.MapPath("~/uploads") + "/" + str);
        string path = "~/uploads" + "/" + str.ToString();
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand("UPDATE tblFilespath SET Name=@Name,Path=@Path WHERE Id = @Id", con);
        cmd.Parameters.AddWithValue("@Name", pname.Text);
        cmd.Parameters.AddWithValue("@Path", path.ToString());
        cmd.Parameters.AddWithValue("@Id", Label3.Text);
        con.Open();
        if (cmd.ExecuteNonQuery() > 0)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Update Successfully!!')", true);
        }
        con.Close();
        BindGrid();
    }
}

protected void btnEdit_Click(object sender, EventArgs e)
{
    Button btn = (sender) as Button;
    GridViewRow row = (GridViewRow)btn.NamingContainer;
    string name = (row.FindControl("pname") as Label).Text;
    string url = (row.FindControl("Image1") as Image).ImageUrl;
    Image2.ImageUrl = url;
    pname.Text = name;
    Label3.Text = (row.FindControl("pid") as Label).Text;
    btnUpdate.Visible = true;
}

protected void submit_Click(object sender, EventArgs e)
{

}
protected void btnClear_Click(object sender, EventArgs e)
{

}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        BindGrid()
    End If
End Sub

Private Sub BindGrid()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("SELECT * FROM tblFilespath", con)
            Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                da.Fill(dt)
                GridView2.DataSource = dt
                GridView2.DataBind()
            End Using
        End Using
    End Using
End Sub

Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs)
    If f1.HasFile = True Then
        Dim str As String = f1.FileName
        f1.PostedFile.SaveAs(Server.MapPath("~/uploads") & "/" & str)
        Dim path As String = "~/uploads" & "/" & str.ToString()
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim con As SqlConnection = New SqlConnection(constr)
        Dim cmd As SqlCommand = New SqlCommand("UPDATE tblFilespath SET Name=@Name,Path=@Path WHERE Id = @Id", con)
        cmd.Parameters.AddWithValue("@Name", pname.Text)
        cmd.Parameters.AddWithValue("@Path", path.ToString())
        cmd.Parameters.AddWithValue("@Id", Label3.Text)
        con.Open()
        If cmd.ExecuteNonQuery() > 0 Then
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "alert", "alert('Update Successfully!!')", True)
        End If
        con.Close()
        BindGrid()
    End If
End Sub

Protected Sub btnEdit_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim btn As Button = TryCast((sender), Button)
    Dim row As GridViewRow = CType(btn.NamingContainer, GridViewRow)
    Dim name As String = (TryCast(row.FindControl("pname"), Label)).Text
    Dim url As String = (TryCast(row.FindControl("Image1"), Image)).ImageUrl
    Image2.ImageUrl = url
    pname.Text = name
    Label3.Text = (TryCast(row.FindControl("pid"), Label)).Text
    btnUpdate.Visible = True
End Sub

Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Screenshot