I am having some problem when trying to get the data keys value from grid view. Here is the code:
GridView gvForCheckBox = (GridView)e.Item.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gvForCheckBox.Rows)
{
//If product name of items in prodList and SPUItemList matches
if (available.Where(x => x.id == gr.Cells[0].Text).Any())
{
//Mark the checkBox checked
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
cb.Checked = true;
//Get the product packaging quantity by productName
string name = gr.Cells[1].Text;
int productQuantity = packBLL.getProductQuantityByName(name);
TextBox tb = (TextBox)gr.Cells[3].FindControl("tbQuantity");
tb.Text = productQuantity.ToString();
}
}
At if (available.Where(x => x.id == gr.Cells[0].Text).Any())
, it's supposed to compare with the value of column 0 row by row, if id matched, then the check box will be marked. However, I did not display an id column in my grid view but I set it as DataKey value. So I wonder how to get the datakey for each row in a grid view.
Thanks in advance.
Assuming x.id
is a string, you can get the DataKey value using gvForCheckBox.DataKeys[gr.RowIndex].Value.ToString()
inside the foreach
loop:
foreach (GridViewRow gr in gvForCheckBox.Rows)
{
//If product name of items in prodList and SPUItemList matches
if (available.Where(x => x.id == gvForCheckBox.DataKeys[gr.RowIndex].Value.ToString()).Any())
{
//Mark the checkBox checked
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
cb.Checked = true;
//Get the product packaging quantity by productName
string name = gr.Cells[1].Text;
int productQuantity = packBLL.getProductQuantityByName(name);
TextBox tb = (TextBox)gr.Cells[3].FindControl("tbQuantity");
tb.Text = productQuantity.ToString();
}
}