I have created a grid view with multiple dynamically generated check boxes but all of the check boxes have same id. How can I get row value of the selected check box?
here is my dyanamic control at gridvie rowdatabound event
protected void grdreport_RowDataBound(object sender, GridViewRowEventArgs e)
{
int temp = e.Row.Cells.Count;
temp--;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (temp >= 3)
{
strheadertext1 = grdreport.HeaderRow.Cells[3].Text;
CheckBox cb1 = new CheckBox();
cb1.ID = "cb1";
cb1.Text = e.Row.Cells[3].Text;
e.Row.Cells[3].Controls.Add(cb1);
}
}
}
and i am getting value on button click
protected void BtnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdreport.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("cb1");
checkbox1.Checked = true;
if (checkbox1.Checked)
{
string itemname = row.Cells[0].Text;
string particular = row.Cells[1].Text;
string qty = row.Cells[2].Text;
}
}
}
but when i am getting value it gives me first row value whenever i check second row checkbox
You are hardcoding you ids. Do something like this:
//(or take the count of something else if this is not suitable)
int i = e.Row.Cells[3].Controls.count + 1;
CheckBox cb1 = new CheckBox();
cb1.ID = "cb" + i;
To find the element in JavaScript:
var checkbox = document.getElementById("checkboxid");
You are looping all the rows, but never store values outside the loop, so the values will always be of the last checkbox checked. Take a look at the following snippet and the values written to Label1
. Those will be the values per row.
protected void BtnSave_Click(object sender, EventArgs e)
{
for (int i = 0; i < grdreport.Rows.Count; i++)
{
GridViewRow row = grdreport.Rows[i];
CheckBox checkbox1 = (CheckBox)row.FindControl("cb1");
if (checkbox1.Checked)
{
Label1.Text += string.Format("Row {0}: {1}<br>", i, row.Cells[1].Text);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.