Как отобразить сообщение с меткой для определенного столбца в сетке? - PullRequest
0 голосов
/ 01 сентября 2018

Это мой маленький фрагмент кода .aspx в виде сетки:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HorizontalAlign="Center" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Quantity" >
<ItemTemplate>
<asp:TextBox ID ="TextBox4" runat="server" Width="60px" DataField="Product_Quantity" Text='<%#Eval("Product_Quantity")%>' />
<asp:Button ID ="Button12" runat="server" OnClick="Quantity_Update_Click" CommandArgument="Button12" CommandName="Update"  Text="Update" />
<asp:Label ID="Label6" runat="server"></asp:Label>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Numbers only" ControlToValidate="TextBox4" ValidationExpression="^[0-9]*$"></asp:RegularExpressionValidator>      
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

А это мой маленький кусочек кода на C #:

 protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UsernameAdmin"] != null && Session["PasswordAdmin"] != null && Session["BranchAdmin"] != null)
            {
                string username = Session["UsernameAdmin"].ToString();
                string password = Session["PasswordAdmin"].ToString();
                string branch = Session["BranchAdmin"].ToString();
                string CS;
                CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
                SqlConnection con = new SqlConnection(CS);
                SqlCommand cmd = new SqlCommand("AdminValidation", con);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@AdministratorUsername", username);
                cmd.Parameters.AddWithValue("@AdministratorPassword", password);
                cmd.Parameters.AddWithValue("@GroceryBranchName", branch);
                con.Open();
                SqlDataReader read = cmd.ExecuteReader();
                read.Read();
                if (read.HasRows == false)
                {
                    Response.Redirect("SignIn.aspx");
                }
                con.Close();
            }

            else
            {
                Response.Redirect("SignIn.aspx");
            }

            Label1.Text = Session["BranchAdmin"].ToString();
            Label2.Text = Session["UsernameAdmin"].ToString();

            if (!Page.IsPostBack)
            {
                DisplayProducts();
            }

        }

 protected void Quantity_Update_Click(object sender, EventArgs e)
        {
            GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
            int index = gvr.RowIndex;
            TextBox box4 = (TextBox)GridView1.Rows[index].Cells[5].FindControl("TextBox4");
            int Quantity;
            bool qty = int.TryParse(box4.Text, out Quantity);

            Button btn = (Button)sender;
            GridViewRow row = (GridViewRow)btn.NamingContainer;
            string ProductNo = row.Cells[0].Text;

            if (Quantity > 0)
            {
                string CS;
                CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
                SqlConnection con = new SqlConnection(CS);
                SqlCommand cmd = new SqlCommand("UpdateProductQuantity", con);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                con.Open();
                cmd.Parameters.AddWithValue("@ProductQuantity", Quantity);
                cmd.Parameters.AddWithValue("@ProductNo", ProductNo);
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox("Quantity has been updated");
                DisplayProducts();
            }

            else if (Quantity == 0 || qty == false)
            {
                Label6.Text = "Please add at least one quantity";
                DisplayProducts();
            }

        }

Теперь проблема в Label6, она отображает красную линию и упоминает, что:

The name 'Label6' does not exist in the current context.

Но я уже добавил Label6 в свой код .aspx. Я не уверен, в чем заключается ошибка, которую я совершаю.

Будет полезно, если будет предложено рекомендуемое синтаксическое решение.

Ответы [ 2 ]

0 голосов
/ 01 сентября 2018

Следующие элементы должны заботиться о ваших потребностях (предполагается, что все ваши ячейки содержат целые числа):

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            // Set the capacity label text
            Label1.Text = e.Row.Cells[0].Text;


            // Calc the sum of all of the row values
            int sum = 0;
            foreach(TableCell c in e.Row.Cells)
            {
                  sum+= Int32.Parse(c.Text);
            }


            // Set the sum label text value
            Label2.Text = sum.ToString();        }
    }

Настройте код, который может вам понадобиться

0 голосов
/ 01 сентября 2018

Так же, как вы находите элемент управления Textbox в сетке по индексу строки, вы также должны найти метку.

Пожалуйста, попробуйте этот код. Конечно, я не могу проверить соединение SQL.

    protected void Quantity_Update_Click(object sender, EventArgs e)
    {
        GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
        int index = gvr.RowIndex;
        TextBox box4 = (TextBox)GridView1.Rows[index].FindControl("TextBox4");
        Label Label6 = (Label)GridView1.Rows[index].FindControl("Label6");
        int Quantity;
        bool qty = int.TryParse(box4.Text, out Quantity);

        Button btn = (Button)sender;
        GridViewRow row = (GridViewRow)btn.NamingContainer;
        string ProductNo = row.Cells[0].Text;

        if (Quantity > 0)
        {
            string CS;
            CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
            SqlConnection con = new SqlConnection(CS);
            SqlCommand cmd = new SqlCommand("UpdateProductQuantity", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            con.Open();
            cmd.Parameters.AddWithValue("@ProductQuantity", Quantity);
            cmd.Parameters.AddWithValue("@ProductNo", ProductNo);
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox("Quantity has been updated");
            DisplayProducts();
        }

        else if (Quantity == 0 || qty == false)
        {
            Label6.Text = "Please add at least one quantity";
            DisplayProducts();
        }

    }

Обратите внимание, что я изменил GridView1.Rows [index], чтобы он не включал часть .Cells [], так как findcontrol будет искать во всей строке элементы управления

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...