Home > Back-end >  How do I maintain editing a row without scrolling back up when I click on the edit button?
How do I maintain editing a row without scrolling back up when I click on the edit button?

Time:10-06

I am working in a ASP.NET project in an empty web application in C# and I have made a gridview with CRUD operations. But when I execute my project and click on the buttons I have made it takes me to the first row and I then have to scroll back down again. It is really annoying but I do not know why it does that. Even though I have used MaintainScrollPositionOnPostBack="true" it does not work. Is there anything I cad add to my code or something I have to be aware of?

Default.aspx

<%@ Page Language="C#" MaintainScrollPositionOnPostBack="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestUsers.Default" %>
<link href="TestUsers.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
  <link rel="stylesheet" href="TestUsers.css">
<link rel="shortcut icon" type="image/x-icon" href="~/orbitone.ico" />


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ESDTESTERS</title>
<%--    <meta http-equiv="refresh" content="20">--%>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div style="margin-left: auto; margin-right: auto; text-align: center;">
                <br /><br />
            <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Sing Out" />

                <br /><br />
                <asp:TextBox ID="TextBox1" runat="server" Width="200px"></asp:TextBox>
                <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" Width="100px" />
                <br />
            </div>

                <asp:GridView ID="gvTestUsers" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="tbl_users_key" ShowHeaderWhenEmpty="True" OnRowCommand="gvTestUsers_RowCommand" OnRowEditing="gvTestUsers_RowEditing" OnRowCancelingEdit="gvTestUsers_RowCancelingEdit" 
                OnRowDeleting="gvTestUsers_RowDeleting" OnRowUpdating="gvTestUsers_RowUpdating" HorizontalAlign="Center" OnPageIndexChanging="gvTestUsers_PageIndexChanged"

                
                BackColor="#CCCCCC" BorderColor="#000000" BorderStyle="Solid" BorderWidth="3px" CellPadding="5" Width="1300px" CellSpacing="2" ForeColor="Black"  PageSize="15" AllowPaging="True" >

                 <%--Theme Properties--%>
                <FooterStyle BackColor="#CCCCCC" />
                <HeaderStyle BackColor="Black" Font-Bold="True" Font-Size="Large" ForeColor="White" />
                <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
                <RowStyle BackColor="White" />
                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#F1F1F1" />
                <SortedAscendingHeaderStyle BackColor="#808080" />
                <SortedDescendingCellStyle BackColor="#CAC9C9" />
                <SortedDescendingHeaderStyle BackColor="#383838" />

                <Columns>
             <asp:TemplateField HeaderText="tbl_users_key">
                 <ItemTemplate>
                     <asp:Label Text='<%# Eval("tbl_users_key") %>' runat="server" />
                 </ItemTemplate>
                 <EditItemTemplate>
                     <asp:TextBox ID="txtID" Text='<%# Eval("tbl_users_key") %>' runat="server" ReadOnly="true" />
                 </EditItemTemplate>
             </asp:TemplateField>

              <asp:TemplateField HeaderText="Name">
                 <ItemTemplate>
                     <asp:Label Text='<%# Eval("Name") %>' runat="server" />
                 </ItemTemplate>
                 <EditItemTemplate>
                     <asp:TextBox ID="txtName" ReadOnly="True" Text='<%# Eval("Name") %>' runat="server" />
                 </EditItemTemplate>
                 <FooterTemplate>
                     <asp:TextBox ID="txtNamefooter" runat="server" />
                 </FooterTemplate>
             </asp:TemplateField>

             <asp:TemplateField HeaderText="CostCenter">
                 <ItemTemplate>
                     <asp:Label Text='<%# Eval("CostCenter") %>' runat="server" />
                 </ItemTemplate>
                 <EditItemTemplate>
                     <asp:TextBox ID="txtCostCenter" ReadOnly="True" Text='<%# Eval("CostCenter") %>' runat="server" />
                 </EditItemTemplate>
                 <FooterTemplate>
                     <asp:TextBox ID="txtCostCenterfooter" runat="server" />
                 </FooterTemplate>
             </asp:TemplateField>

              <asp:TemplateField HeaderText="Employee">
                 <ItemTemplate>
                     <asp:Label Text='<%# Eval("Employee") %>' runat="server" />
                 </ItemTemplate>
                 <EditItemTemplate>
                     <asp:TextBox ID="txtEmployee" ReadOnly="True" Text='<%# Eval("Employee") %>' runat="server" />
                 </EditItemTemplate>
                 <FooterTemplate>
                     <asp:TextBox ID="txtEmployeefooter" runat="server" />
                 </FooterTemplate>
             </asp:TemplateField>

                    
              <asp:TemplateField HeaderText="FootPlate">
                 <ItemTemplate>
                     <asp:Label Text='<%# Eval("FootPlate") %>' runat="server" />
                 </ItemTemplate>
                 <EditItemTemplate>
                     <asp:TextBox ID="txtFootPlate" Text='<%# Eval("FootPlate") %>' runat="server" />
                 </EditItemTemplate>
                 <FooterTemplate>
                     <asp:TextBox ID="txtFootPlatefooter" runat="server" />
                 </FooterTemplate>
             </asp:TemplateField>

                    <asp:TemplateField HeaderText="WirstCord">
                 <ItemTemplate>
                     <asp:Label Text='<%# Eval("WirstCord") %>' runat="server" />
                 </ItemTemplate>
                 <EditItemTemplate>
                     <asp:TextBox ID="txtWirstCord" Text='<%# Eval("WirstCord") %>' runat="server" />
                 </EditItemTemplate>
                 <FooterTemplate>
                     <asp:TextBox ID="txtWirstCordfooter" runat="server" />
                 </FooterTemplate>
             </asp:TemplateField>

                    <asp:TemplateField HeaderText="Excluded">
                 <ItemTemplate>
                     <asp:Label Text='<%# Eval("Excluded") %>' runat="server" />
                 </ItemTemplate>
                 <EditItemTemplate>
                     <asp:TextBox ID="txtExcluded" Text='<%# Eval("Excluded") %>' runat="server" />
                 </EditItemTemplate>
                 <FooterTemplate>
                     <asp:TextBox ID="txtExcludedfooter" runat="server" />
                 </FooterTemplate>
             </asp:TemplateField>

                    <asp:TemplateField HeaderText="Comment">
                 <ItemTemplate>
                     <asp:Label Text='<%# Eval("Comment") %>' runat="server" />
                 </ItemTemplate>
                 <EditItemTemplate>
                     <asp:TextBox ID="txtComment" Text='<%# Eval("Comment") %>' runat="server" />
                 </EditItemTemplate>
                 <FooterTemplate>
                     <asp:TextBox ID="txtCommentfooter" runat="server" />
                 </FooterTemplate>
             </asp:TemplateField>

                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:ImageButton ImageUrl="~/GridImages/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px" /> 
                            <asp:ImageButton ImageUrl="~/GridImages/delete.png" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" ToolTip="Delete" Width="20px" Height="20px" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:ImageButton ImageUrl="~/GridImages/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px" /> 
                            <asp:ImageButton ImageUrl="~/GridImages/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:ImageButton ImageUrl="~/GridImages/add.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px" />
                        </FooterTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <br />

            <div style="margin-left: auto; margin-right: auto; text-align: center;">
            <asp:Label ID="lblSuccessMessage" Text="" runat="server" ForeColor="Green" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
            <br />
            <asp:Label ID="lblErrorMessage" Text="" runat="server" ForeColor="Red" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
            </div>

            

        </div>
    </form>


</body>
</html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace TestUsers
{

    public partial class Default : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);

        string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateGridView();
            }
        }


        void PopulateGridView()
        {
            DataTable dtbl = new DataTable();
            string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                sqlCon.Open();
                SqlDataAdapter sqlDa = new SqlDataAdapter("Select * FROM TBL_USERS", sqlCon);
                sqlDa.Fill(dtbl);
            }
            if (dtbl.Rows.Count > 0)
            {
                gvTestUsers.DataSource = dtbl;
                gvTestUsers.DataBind();
            }
            else
            {
                dtbl.Rows.Add(dtbl.NewRow());
                gvTestUsers.DataSource = dtbl;
                gvTestUsers.DataBind();
                gvTestUsers.Rows[0].Cells.Clear();
                gvTestUsers.Rows[0].Cells.Add(new TableCell());
                gvTestUsers.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count;
                gvTestUsers.Rows[0].Cells[0].Text = "No Data Found.";
                gvTestUsers.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
            }
        }
        

        protected void gvTestUsers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName.Equals("AddNew"))
                {


                    int tbl_users_key = 0;

                    TextBox myTxt;

                    myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtNamefooter"));
                    string Name;
                    Name = myTxt.Text;

                    string CostCenter;
                    myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCostCenterfooter"));
                    CostCenter = myTxt.Text;

                    string Employee;
                    myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtEmployeefooter"));
                    Employee = myTxt.Text;

                    Boolean  FootPlate;
                    myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtFootPlatefooter"));
 
                    FootPlate = Convert.ToBoolean(myTxt.Text);

                    Boolean WirstCord;
                    myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtWirstCordfooter"));
                    WirstCord = Convert.ToBoolean(myTxt.Text);

                    Boolean Excluded;
                    myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtExcludedfooter"));
                    Excluded = Convert.ToBoolean(myTxt.Text);

                    string Comment;
                    myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCommentfooter"));
                    Comment = myTxt.Text;


                    string sMsg;

                    sMsg = "";


                   bool btest = fcEditTBL_USERS(tbl_users_key, Name, CostCenter, Employee, FootPlate, WirstCord, Excluded, Comment, ref sMsg,0);


                    if (btest == false)
                    {
                        lblErrorMessage.Text = sMsg;
                        lblSuccessMessage.Text = " ";
                        return;
                    }

                    PopulateGridView();

                    lblSuccessMessage.Text = Name   " Was Added To Record.";
                }
            }
            catch (Exception ex)
            {
                lblSuccessMessage.Text = "";
                lblErrorMessage.Text = ex.Message;
            }
        }

        protected void gvTestUsers_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvTestUsers.EditIndex = e.NewEditIndex;
            PopulateGridView();
        }

        protected void gvTestUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvTestUsers.EditIndex = -1;
            PopulateGridView();
        }


        protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            try
            {

                {


                    gvTestUsers.EditIndex = e.RowIndex;
                    PopulateGridView();
                   

                    //Parameters for delete operation
                    string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
                    string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
                    string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
                    string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
                    string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
                    string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
                    string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
                    string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
                    string dltsMsg = "";


                    //Call function for SP_Delete
                    bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, Convert.ToBoolean(dltFootPlate), Convert.ToBoolean(dltWirstCord), Convert.ToBoolean(dltExcluded), dltComment,ref dltsMsg,2);

                    if (FuncDelete == false)
                    {
                        lblErrorMessage.Text = dltsMsg;
                        lblSuccessMessage.Text = " ";
                        return;
                    }



                    PopulateGridView();
                    lblSuccessMessage.Text = "Selected Record Deleted.";
                    lblErrorMessage.Text = "";


                    gvTestUsers.EditIndex = -1;


                }
            }
            catch (Exception ex)
            {
                lblSuccessMessage.Text = "";
                lblErrorMessage.Text = ex.Message;
            }
        }



        
            public bool fcEditTBL_USERS
            (int tbl_users_key, string Name, string CostCenter, string Employee, bool FootPlate, bool WirstCord, bool Excluded, string Comment, ref string sMsg, int iMode)
            {
            
            string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
              



                try
                {



                    sqlCon.Open();

                    SqlCommand sqlCmd = new SqlCommand("spEditTBL_USERS", sqlCon);




                    sqlCmd.CommandType = CommandType.StoredProcedure;


               
                    SqlParameter returnParameter = sqlCmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", DbType.Int32));
                    returnParameter.Direction = ParameterDirection.ReturnValue;


                    sqlCmd.Parameters.Add("@ID", SqlDbType.Int).Value=tbl_users_key ;

                    sqlCmd.Parameters.Add("@Name", SqlDbType.VarChar, 255).Value=Name;
                    sqlCmd.Parameters.Add("@CostCenter", SqlDbType.VarChar, 10).Value=CostCenter;
                    sqlCmd.Parameters.Add("@Employee", SqlDbType.VarChar, 32).Value=Employee;
                    sqlCmd.Parameters.Add("@FootPlate", SqlDbType.Bit).Value=FootPlate;
                    sqlCmd.Parameters.Add("@WirstCord", SqlDbType.Bit).Value=WirstCord;
                    sqlCmd.Parameters.Add("@Excluded", SqlDbType.Bit).Value=Excluded;
                    sqlCmd.Parameters.Add("@Comment", SqlDbType.VarChar, 255).Value=Comment;
                    sqlCmd.Parameters.Add("@MODE", SqlDbType.SmallInt).Value  =iMode;

                    sqlCmd.Parameters.Add("@MSG", SqlDbType.NVarChar, 255).Value=sMsg;
                    sqlCmd.Parameters["@MSG"].Direction = ParameterDirection.Output;
                    sqlCmd.ExecuteNonQuery();
                    sMsg = sqlCmd.Parameters["@MSG"].Value.ToString();
                    int rtn = (int)sqlCmd.Parameters["@RETURN_VALUE"].Value;

                    if (rtn != 0)
                    {
                        return false;

                    }
                    sqlCmd.Dispose();

                    return true;
                }
                finally
                {

                }
            }



        protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

                try
                {
                //Parameters Set From Grid
                    string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
                    string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
                    string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
                    string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
                    string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
                    string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
                    string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
                    string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
                    string tmpsMsg = "";

                    //Call function for SP_UPDATE
                    bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, Convert.ToBoolean(tmpFootPlate), Convert.ToBoolean(tmpWirstCord), Convert.ToBoolean(tmpExcluded), tmpComment,ref tmpsMsg,1);
                    //Reload Page
                    PopulateGridView();
                    lblSuccessMessage.Text = "Selected Record Updated.";
                    lblErrorMessage.Text = "";
                }
                catch (Exception ex)
                {
                    lblSuccessMessage.Text = "";
                    lblErrorMessage.Text = ex.Message;
                }
        }

        protected void gvTestUsers_PageIndexChanged(object sender, GridViewPageEventArgs e)
        {
            gvTestUsers.PageIndex = e.NewPageIndex;
            PopulateGridView();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string find = "select * from TBL_USERS where (Name like '%'   @Name   '%') or (employee like '%'   @Employee   '%')";
            SqlCommand comm = new SqlCommand (find,con);
            comm.Parameters.Add("@Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
            comm.Parameters.Add("@Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
            con.Open();
            comm.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = comm;
            DataSet ds = new DataSet();
            da.Fill(ds, "Name");
            da.Fill(ds, "Employee");
            gvTestUsers.DataSource = ds;
            gvTestUsers.DataBind();
            con.Close();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
          Response.Redirect("LoginForm.aspx");
        }

    }
}

CodePudding user response:

Thank you for the explanation. Please try setting gridview editindex before populating the gridview (after updating and deleting ) Hope this helps. Working below code for me.

protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

    try
    {
        //Parameters Set From Grid
        string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
        string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
        string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
        string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
        string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
        string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
        string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
        string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
        string tmpsMsg = "";

        //Call function for SP_UPDATE
      bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, tmpFootPlate, tmpWirstCord, tmpExcluded, tmpComment, ref tmpsMsg, "Update");

        //add this 
        gvTestUsers.EditIndex = -1;
        PopulateGridView();

        lblSuccessMessage.Text = "Selected Record Updated.";
        lblErrorMessage.Text = "";
    }
    catch (Exception ex)
    {
        lblSuccessMessage.Text = "";
        lblErrorMessage.Text = ex.Message;
    }
}

And the row deleting below,

protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

    try
    {

        {


            gvTestUsers.EditIndex = e.RowIndex;
            PopulateGridView();


            //Parameters for delete operation
            string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
            string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
            string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
            string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
            string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
            string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
            string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
            string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
            string dltsMsg = "";


            //Call function for SP_Delete
           bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, dltFootPlate, dltWirstCord,dltExcluded, dltComment, ref dltsMsg, "Delete");

            if (FuncDelete == false)
            {
                lblErrorMessage.Text = dltsMsg;
                lblSuccessMessage.Text = " ";
                return;
            }


            gvTestUsers.EditIndex = -1;
            PopulateGridView();
            lblSuccessMessage.Text = "Selected Record Deleted.";
            lblErrorMessage.Text = "";

        }
    }
    catch (Exception ex)
    {
        lblSuccessMessage.Text = "";
        lblErrorMessage.Text = ex.Message;
    }
}

CodePudding user response:

I solved it by moving the SearchBox-Event code into my PopulateGridView. So now the PopulateGridView looks like this:

void PopulateGridView()
        {
            string find = "select * from TBL_USERS where (Name like '%'   @Name   '%') or (employee like '%'   @Employee   '%')";
            SqlCommand comm = new SqlCommand(find, con);
            comm.Parameters.Add("@Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
            comm.Parameters.Add("@Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
            con.Open();
            comm.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = comm;
            DataSet ds = new DataSet();
            da.Fill(ds, "Name");
            da.Fill(ds, "Employee");
            gvTestUsers.DataSource = ds;
            gvTestUsers.DataBind();
            con.Close();
}

And the Searchbox-Event:

protected void Button1_Click(object sender, EventArgs e)
        {
            PopulateGridView();
}

Else it would jump straight to Void PopulateGridView each time I would try to use an EDIT,CREATE or DELETE operation.

  • Related