这就是我的 gridview 的样子:
基本上,我选择“你”作为正确答案。
但是在我点击“+”按钮后,单选按钮的选择被删除了。
如何为每一行 gridview 保留我对单选按钮的选择?
这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
dropActivity(); // ignore this , this is for drop down list
dropTask(); // ignore this , this is for drop down list
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Question", typeof(string)));
dt.Columns.Add(new DataColumn("Hints No.1", typeof(string)));
dt.Columns.Add(new DataColumn("Hints No.2", typeof(string)));
dr = dt.NewRow();
dr["Question"] = string.Empty;
dr["Hints No.1"] = string.Empty;
dr["Hints No.2"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["Question"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Hints No.1"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Hints No.2"] = box3.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
// Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
RadioButton radiobtn1 = (RadioButton)GridView1.Rows[i].Cells[2].FindControl("RadioButton1");
RadioButton radiobtn2 = (RadioButton)GridView1.Rows[i].Cells[3].FindControl("RadioButton2");
//Setting previous text to the respective textboxes based on columns.
box1.Text = dt.Rows[i]["Question"].ToString();
box2.Text = dt.Rows[i]["Hints No.1"].ToString();
box3.Text = dt.Rows[i]["Hints No.2"].ToString();
if (radiobtn1.Checked == true)
{
ViewState["RadioButtonStatus"] = radiobtn1.Checked;
}
if (radiobtn2.Checked == true)
{
ViewState["RadioButtonStatus"] = radiobtn2.Checked;
}
Session["Question1"] = box1.Text;
rowIndex++;
}
}
}
}
基本上我需要为我创建的每一行保留单选按钮的选择。