如何在网格视图中显示特定列的标签消息?

时间:2018-09-01 08:27:36

标签: c# asp.net aspxgridview

这是我在网格视图下的一小段.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.

但是我已经在我的.aspx代码中添加了Label6。 我不确定我在哪里犯错。

如果提供了建议的语法解决方案,将会很有帮助。

2 个答案:

答案 0 :(得分:1)

就像您通过rowindex在网格中找到一个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将在整行中查找控件

答案 1 :(得分:0)

以下内容应满足您的需求(假设您所有的单元格都包含整数):

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();        }
    }

根据需要调整代码