如何在GridView中获取特定的调用值

时间 2019-02-22
阅读 32
点赞 0
收藏 0
连接asad

我实际上使用了一个网格视图表来显示一些产品属性,如名称、价格和数量。然后,在调用Datashow_RowUpdating函数i减去数量单元格的值。现在我想得到同一个产品的名称,并将其保存在一个列表中并打印出来,但我无法得到该产品的名称。我尝试过不同的方法,比如Datashow.Rows[e.RowIndex].Cells[2].Text.ToString();
但没有运气。我附加了包含更新代码的更新功能,请帮助!!!!!!! 谢谢

protected void Datashow_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    try
    {
        using (SqlConnection sqlcon = new SqlConnection(connectionstring))
        {
            //ObjectQuery<Med> filteredproduct = new ObjectQuery<Med>("Select Value p From Med AS p ",Med);
            //LstProductsChosen.DataSource = products;
            //LstProductsChosen.DataValueField = "ID";
            //LstProductsChosen.DataTextField = "Name";


            sqlcon.Open();
            string query = "UPDATE Med SET Quantity = Quantity - @Quantity WHERE ID=@id";
            //Med q = new Med { Name = "eee" , Company = "new" };
            SqlCommand cmd = new SqlCommand(query, sqlcon);
            //cmd.Parameters.AddWithValue("@Quantity", (Datashow.Rows[e.RowIndex].FindControl("TextQuantity") as TextBox).Text.Trim());

            cmd.Parameters.AddWithValue("@Quantity", (Datashow.Rows[e.RowIndex].FindControl("TextQuantity") as System.Web.UI.WebControls.TextBox).Text.Trim());
            cmd.Parameters.AddWithValue("id", Convert.ToInt32(Datashow.DataKeys[e.RowIndex].Value.ToString()));
            cmd.ExecuteNonQuery();
            Datashow.EditIndex = -1;
            populategridview();
            Addinlist();
            GridViewRow row = Datashow.Rows[e.RowIndex];

            string c = Datashow.Rows[e.RowIndex].Cells[2].Text.ToString();
            Console.WriteLine(c);
            Med q = new Med()
            {
                Name = c ,
                Price = 100,
                Company = "Reck",
                Discount = 10,
                Expiry = 2018,
                Potency = "30",
                Quantity = 10,
                Size = "10ml"
            };
            meds.Add(q);
            LstProductsChosen.Items.Add("q" + q.Name);

            //LblSucessMsg.Text = "selected " + row.Cells[2].Text;
        }
    }
    catch (Exception ex)
    {
        LblSucessMsg.Text = "";
        LblErrorMsg.Text = ex.Message;
    }
}
建议答案

更简单的方法是获取当前选定行:

GridViewRow row = DataShow.SelectedRow;

// And you respective cell's value
string textValue = row.Cells[2].Text;

注意:单元格是基于0索引的。第一个单元格是0索引,第二个单元格是1索引,依此类推。

您也可以尝试以下操作:

GridViewRow row = DataShow.Rows[e.RowIndex];
String textValue = ((TextBox)(row.Cells[2].Controls[0])).Text;
👍 0