如何在gridview内以编程方式创建的文本框中获取和保存值?

时间:2016-01-08 04:19:38

标签: c# asp.net gridview textbox postback

我的gridview包含在

后面的代码中创建的文本框

这是页面加载:

protected void Page_Load(object sender, EventArgs e)
{
    //my page load is empty;
}

这里是选择下拉菜单后按钮的代码,然后点击“Pilih”显示包含文本框的gridview:

public void btnPilihKrit_Click(object sender, EventArgs e)
{
    DataTable dtsubKrit = new DataTable();
    dtsubKrit = subkritMgr.getListSubKriteriaByIDKriteria(int.Parse(ddlKrit.SelectedValue));
    NbDtSubKritRow = dtsubKrit.Rows.Count;

    dtGvSubKrit.Columns.Add(new DataColumn("SUBKRITERIA", typeof(string)));
    foreach (DataRow row in dtsubKrit.Rows)
    {
        dtGvSubKrit.Columns.Add(new DataColumn(row["SUBKRITERIA"].ToString(), typeof(string)));
    }
    DataRow dr = null;

    foreach (DataRow row in dtsubKrit.Rows)
    {
        dr = dtGvSubKrit.NewRow();
        dr["SUBKRITERIA"] = row["SUBKRITERIA"];
        dtGvSubKrit.Rows.Add(dr);
    }


    gvKrit2.DataSource = dtGvSubKrit;
    gvKrit2.DataBind();

    ViewState["CurrentTable"] = dtGvSubKrit;
}

这是gridview的rowdatabound中的代码:

protected void gvKrit2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 1; i <= NbDtSubKritRow; i++)
        {
            TextBox txtNilai = new TextBox();
            txtNilai.ID = "txtNilai" + e.Row.RowIndex.ToString() + i.ToString();
            if (i == e.Row.RowIndex + 1)
            {
                txtNilai.Text = "1";
            }
            else
            {
                txtNilai.Text = "";
            }
            if (i <= e.Row.RowIndex + 1)
            {
                txtNilai.Enabled = false;
            }
            e.Row.Cells[i].Controls.Add(txtNilai);
        }

    }

}

然后这是从网格视图中的文本框中获取值的代码:

protected void btnProsesPerbBerpsg_Click(object sender, EventArgs e)
{

    foreach (GridViewRow row in gvKrit2.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            TextBox textBox = row.FindControl("txtNilai") as TextBox;
            string tb = textBox.Text;
            // do somthing with the text box textBox
        }
    }
}

以下是一些例子:

  1. Screenshot 1,点击按钮Pilih并选择下拉菜单后,将显示带文本框的gridview,我将用自己的值填充文本框
  2. Screenshot 2,点击按钮“Proses Perbandingan Berpasangan”从gridview获取价值
  3. 谁能帮帮我?

    我尝试了许多方式,如

    TextBox box1 = (TextBox)(gvKrit2.Rows[rowIndex].Cells[1].FindControl("txtNilai")) as TextBox;
    

    但是findcontrol找不到文本框。好像gridview在帖子后面不再创建。

    我搜索了一些文献,我必须重新创建gridview或在gridview中创建rowcreated事件,但现在我不知道这样做。

1 个答案:

答案 0 :(得分:0)

在RowDataBound上创建文本框时ID如下:

 txtNilai.ID = "txtNilai" + e.Row.RowIndex.ToString() + i.ToString();

所以你需要找到那个ID:

string txtid = "txtNilai"+e.Row.RowIndex.ToString()+i.ToString(); // as per given inRowdataBound , so make sure to define i value.
TextBox textBox = row.FindControl(txtid) as TextBox;