简体   繁体   English

即使我在 page_load 中有一个 !postback,OnRowUpdating 也不起作用

[英]OnRowUpdating does not work even if i have a !postback in page_load

I am a beginner and I am creating a crud webpage in asp.net and i can't get the update(save) button working.我是初学者,我正在 asp.net 中创建一个 crud 网页,但我无法使更新(保存)按钮工作。 here is the snippet of my code:这是我的代码片段:

Save and Cancel buttons in Main.aspx Main.aspx 中的保存和取消按钮

<div  height: 334px;" class="gridview">
            <asp:GridView ID="RetailInfoGridView"
                AutoGenerateColumns="False"
                ShowFooter="true"
                DataKeyNames="StockKeepingID"
                runat="server"
                ShowHeaderWhenEmpty="True"
                HeaderStyle-ForeColor="White"
                AlternatingRowStyle="alt"
                EmptyDataText="No Records Found"
                AllowSorting="True"
                OnRowCommand="RetailInfoGridView_RowCommand"
                OnDataBound="RetailInfoGridView_DataBound"
                OnRowDataBound="RetailInfoGridView_RowDataBound"
                OnRowEditing="RetailInfoGridView_RowEditing"
                OnRowCancelingEdit="RetailInfoGridView_RowCancelingEdit"
                OnRowUpdating="RetailInfoGridView_RowUpdating"
                onRowDeleting="RetailInfoGridView_RowDeleting"
                OnSelectedIndexChanged="RetailInfoGridView_SelectedIndexChanged">

                <Columns>

                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Button ID="Edit" CommandName="Edit" runat="server" Text="Edit" ToolTip="Edit" />
                            <asp:Button ID="Delete" CommandName="Delete" runat="server" Text="Delete" ToolTip="Delete" />
                        </ItemTemplate>

                        <EditItemTemplate>
                            <asp:Button ID="Save" CommandName="Save" runat="server" Text="Save" ToolTip="Save" />
                            <asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
                        </EditItemTemplate>

                        <FooterTemplate>
                            <asp:Button ID="Add" CommandName="Add" runat="server" Text="Add" ToolTip="Add" />
                        </FooterTemplate>

</asp:TemplateField>

<EditItemTemplate>
                            <asp:Button ID="Save" CommandName="Save" runat="server" Text="Save" ToolTip="Save" />
                            <asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>

...

Main.aspx.cs主.aspx.cs


 string connectionString = "Data Source=102000-LSU-2216;Initial Catalog=loginDB;Integrated Security=True";

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

        protected void SearchTextBox_TextChanged(object sender, EventArgs e)
        {
            /* connect.Open();
             string query = "SELECT * FROM RetailInfo WHERE StockKeepingUnit LIKE '%" + SearchTextBox.Text + "%'";
             adapter = new SqlDataAdapter(query, connect);
             table = new DataTable();
             adapter.Fill(table);
             RetailInfoGridView.DataSource = table; 
             RetailInfoGridView.DataBind();

             connect.Close();*/
        }

        protected void SearchButton_Click(object sender, EventArgs e)
        {

            using (SqlConnection connect = new SqlConnection(connectionString))
            {
                connect.Open();
                SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM RetailInfo WHERE StockKeepingUnit LIKE '%" + SearchTextBox.Text + "%'", connect);
                DataTable table = new DataTable();
                adapter.Fill(table);


                RetailInfoGridView.DataSource = table;
                RetailInfoGridView.DataBind();

            }

        }

        protected void RetailInfoGridView_DataBound(object sender, EventArgs e)
        {

        }

        protected void RetailInfoGridView_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void RetailInfoGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
                e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
                e.Row.ToolTip = "Click the link to view Description";

                //e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(RetailInfoGridView, "Select$" + e.Row.RowIndex);
            }
        }

        void PopulateGridView()
        {
            using (SqlConnection connect = new SqlConnection(connectionString))
            {
                connect.Open();
                SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM RetailInfo", connect);
                DataTable table = new DataTable();
                adapter.Fill(table);


                if (table.Rows.Count > 0)
                {
                    RetailInfoGridView.DataSource = table;
                    RetailInfoGridView.DataBind();
                }
                else
                {
                    table.Rows.Add(table.NewRow());
                    RetailInfoGridView.DataSource = table;
                    RetailInfoGridView.DataBind();
                    RetailInfoGridView.Rows[0].Cells.Clear();
                    RetailInfoGridView.Rows[0].Cells.Add(new TableCell());
                    RetailInfoGridView.Rows[0].Cells[0].ColumnSpan = table.Columns.Count;
                    RetailInfoGridView.Rows[0].Cells[0].Text = "No record Found";

                }
            }

        }

        protected void RetailInfoGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {

                if (e.CommandName.Equals("Add"))
                {
                    using (SqlConnection connect = new SqlConnection(connectionString))
                    {
                        connect.Open();
                        string query = "INSERT INTO RetailInfo(StockKeepingUnit,UniversalProductCode,VendorName,ProductName,ProductDesc,RetailPrice) VALUES (@StockKeepingUnit,@UniversalProductCode,@VendorName,@ProductName,@ProductDesc,@RetailPrice)";
                        SqlCommand command = new SqlCommand(query, connect);
                        command.Parameters.AddWithValue("@StockKeepingUnit", (RetailInfoGridView.FooterRow.FindControl("skuTextBoxFooter") as TextBox).Text.Trim());
                        command.Parameters.AddWithValue("@UniversalProductCode", (RetailInfoGridView.FooterRow.FindControl("upcTextBoxFooter") as TextBox).Text.Trim());
                        command.Parameters.AddWithValue("@VendorName", (RetailInfoGridView.FooterRow.FindControl("vnTextBoxFooter") as TextBox).Text.Trim());
                        command.Parameters.AddWithValue("@ProductName", (RetailInfoGridView.FooterRow.FindControl("pnTextBoxFooter") as TextBox).Text.Trim());
                        command.Parameters.AddWithValue("@ProductDesc", (RetailInfoGridView.FooterRow.FindControl("pdTextBoxFooter") as TextBox).Text.Trim());
                        command.Parameters.AddWithValue("@RetailPrice", (RetailInfoGridView.FooterRow.FindControl("rpTextBoxFooter") as TextBox).Text.Trim());
                        command.ExecuteNonQuery();
                        PopulateGridView();
                        ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('New Record Added');", true);
                    }
                }
            }
            catch (Exception ex)
            {

            }   

        }

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

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

        protected void RetailInfoGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {

                using (SqlConnection connect = new SqlConnection(connectionString))
                {
                    connect.Open();
                    string query = "UPDATE RetailInfo SET StockKeepingUnit=@StockKeepingUnit,UniversalProductCode=@UniversalProductCode,VendorName=@VendorName,ProductName=@ProductName,ProductDesc=@ProductDesc,RetailPrice=@RetailPrice WHERE StockKeepingID=@id";
                    SqlCommand command = new SqlCommand(query, connect);
                    command.Parameters.AddWithValue("@StockKeepingUnit", (RetailInfoGridView.Rows[e.RowIndex].FindControl("skuTextBox") as TextBox).Text.Trim());
                    command.Parameters.AddWithValue("@UniversalProductCode", (RetailInfoGridView.Rows[e.RowIndex].FindControl("upcTextBox") as TextBox).Text.Trim());
                    command.Parameters.AddWithValue("@VendorName", (RetailInfoGridView.Rows[e.RowIndex].FindControl("vnTextBox") as TextBox).Text.Trim());
                    command.Parameters.AddWithValue("@ProductName", (RetailInfoGridView.Rows[e.RowIndex].FindControl("pnTextBox") as TextBox).Text.Trim());
                    command.Parameters.AddWithValue("@ProductDesc", (RetailInfoGridView.Rows[e.RowIndex].FindControl("pdTextBox") as TextBox).Text.Trim());
                    command.Parameters.AddWithValue("@RetailPrice", (RetailInfoGridView.Rows[e.RowIndex].FindControl("rpTextBox") as TextBox).Text.Trim());
                    command.Parameters.AddWithValue("@id", Convert.ToInt32(RetailInfoGridView.DataKeys[e.RowIndex].Value.ToString()));
                    command.ExecuteNonQuery();
                    RetailInfoGridView.EditIndex = -1;
                    PopulateGridView();
                    ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('Record Updated');", true);
                }

            }
            catch (Exception ex)
            {

            }
        }

        protected void RetailInfoGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                using (SqlConnection connect = new SqlConnection(connectionString))
                {
                    connect.Open();
                    string query = "DELETE FROM RetailInfo WHERE StockKeepingID = @id";
                    SqlCommand command = new SqlCommand(query, connect);
                    command.Parameters.AddWithValue("@id", Convert.ToInt32(RetailInfoGridView.DataKeys[e.RowIndex].Value.ToString()));
                    command.ExecuteNonQuery();
                    PopulateGridView();
                    ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('Record Deleted');", true);
                }

            }
            catch (Exception ex)
            {

            }
        }

Whenever I run the program, I edit values to a specific row and then I click the save button, it does not do anything.每当我运行程序时,我都会将值编辑到特定行,然后单击保存按钮,它不会执行任何操作。 I have read other answers that said to have a !postback and DataKeyNames in the code but I already have the postback in Main.aspx.cs and the DataKeyNames on Main.aspx.我读过其他答案,说代码中有 !postback 和 DataKeyNames,但我已经在 Main.aspx.cs 和 Main.aspx 上有 DataKeyNames 的回发。 I don't know if the error comes on the .aspx or on the .aspx.cs.我不知道错误是在 .aspx 上还是在 .aspx.cs 上。 Have I done something wrong on the code?我在代码上做错了吗? any help would be highly appreciated.任何帮助将不胜感激。 Thank you.谢谢你。

UPDATE:更新:

I have solved the problem.我已经解决了这个问题。 instead of writing "save" variables:而不是编写“保存”变量:

<EditItemTemplate>
        <asp:Button ID="Save" CommandName="Save" runat="server" Text="Save" ToolTip="Save" />
        <asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>

I changed it to "update":我将其更改为“更新”:

<EditItemTemplate>
         <asp:Button ID="Update" CommandName="Update" runat="server" Text="Update" ToolTip="Update" />
         <asp:Button ID="Cancel" CommandName="Cancel" runat="server" Text="Cancel" ToolTip="Cancel" />
</EditItemTemplate>

Although I do not know why it worked, but it did the job!虽然我不知道它为什么起作用,但它确实起作用了!

If you know why "save" did not work and and "update" worked, I would really appreciate it if you tell me so i can be enlightened.如果您知道为什么“保存”不起作用而“更新”起作用,如果您告诉我,我将不胜感激,这样我才能有所启发。

Thank you for all who helped.感谢所有帮助过的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM