簡體   English   中英

如何使用javascript在gridview中獲取動態創建的復選框行值

[英]how to get dynamically created checkbox row value in gridview using javascript

我創建了帶有多個動態生成的復選框的網格視圖,但是所有復選框都具有相同的ID。 如何獲取所選復選框的行值?

這是我在gridvie rowdatabound事件上的動態控件

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

而且我在單擊按鈕時就獲得了價值

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

但是當我獲得價值時,只要我選中第二行復選框,它就會給我第一行價值

您正在對ID進行硬編碼。 做這樣的事情:

//(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;

在JavaScript中查找元素:

var checkbox = document.getElementById("checkboxid");

您正在循環所有行,但是永遠不要將值存儲在循環外,因此這些值將始終是最后一個選中的復選框。 看看下面的代碼片段和寫入Label1的值。 這些將是每行的值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM