Handle event in dynamically created button in Gridview - c#

I have created dynamic textboxs and dropdownlist in gridview. It is working perfectly. Further I want to fire event in dynamic dropdownlist and do some action.
private ArrayList GetDummyData() {
ArrayList arr = new ArrayList();
arr.Add(new ListItem("Item1", "1"));
arr.Add(new ListItem("Item2", "2"));
arr.Add(new ListItem("Item3", "3"));
arr.Add(new ListItem("Item4", "4"));
arr.Add(new ListItem("Item5", "5"));
return arr;
}
private void FillDropDownList(DropDownList ddl) {
ArrayList arr = GetDummyData();
foreach (ListItem item in arr) {
ddl.Items.Add(item);
}
}
private void SetInitialRow() {
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for DropDownList selected item
dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for DropDownList selected item
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Bind the Gridview
Gridview1.DataSource = dt;
Gridview1.DataBind();
//After binding the gridview, we can then extract and fill the DropDownList with Data
DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[0].Cells[4].FindControl("DropDownList2");
FillDropDownList(ddl1);
FillDropDownList(ddl2);
}
private void AddNewRowToGrid() {
if (ViewState["CurrentTable"] != null) {
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0) {
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState for future reference
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++) {
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
dtCurrentTable.Rows[i]["Column1"] = box1.Text;
dtCurrentTable.Rows[i]["Column2"] = box2.Text;
//extract the DropDownList Selected Items
DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[i].Cells[4].FindControl("DropDownList2");
// Update the DataRow with the DDL Selected Items
dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column4"] = ddl2.SelectedItem.Text;
}
//Rebind the Grid with the current data to reflect changes
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[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[4].FindControl("DropDownList2");
//Fill the DropDownList with Data
FillDropDownList(ddl1);
FillDropDownList(ddl2);
if (i < dt.Rows.Count - 1) {
//Assign the value from DataTable to the TextBox
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
//Set the Previous Selected Items on Each DropDownList on Postbacks
ddl1.ClearSelection();
ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;
ddl2.ClearSelection();
ddl2.Items.FindByText(dt.Rows[i]["Column4"].ToString()).Selected = true;
}
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
SetInitialRow();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e) {
AddNewRowToGrid();
}
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
DataTable dt = (DataTable)ViewState["CurrentTable"];
LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1");
if (lb != null) {
if (dt.Rows.Count > 1) {
if (e.Row.RowIndex == dt.Rows.Count - 1) {
lb.Visible = false;
}
}
else {
lb.Visible = false;
}
}
}
}
protected void LinkButton1_Click(object sender, EventArgs e) {
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex;
if (ViewState["CurrentTable"] != null) {
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1) {
if (gvRow.RowIndex < dt.Rows.Count - 1) {
//Remove the Selected Row data and reset row number
dt.Rows.Remove(dt.Rows[rowID]);
ResetRowID(dt);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void ResetRowID(DataTable dt) {
int rowNumber = 1;
if (dt.Rows.Count > 0) {
foreach (DataRow row in dt.Rows) {
row[0] = rowNumber;
rowNumber++;
}
}
}

Might be a duplicate of question:
how to add an OnClick event on DropDownList's ListItem that is added dynamically?
Please check the answer given there.
DropDownList changesList = new DropDownList();
ListItem item;
item = new ListItem();
item.Text = "go to google.com";
item.Value = "http://www.google.com";
changesList.Items.Add(item);
changesList.Attributes.Add("onChange", "location.href = this.options[this.selectedIndex].value;");
Also have you tried adding a handler to the event SelectedIndexChanged dynamically when adding the new row to the grid?

Related

Deleting Row from Grid view without using Database

I am using this code to delete rows from grid view and the rows are getting deleted but when I add a new row to my Grid view the deleted row comes back again any suggestions what should I do to delete row from my grid view and I am not using database on it. Thanks in Advance.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("EmpId", typeof(string)));
dt.Columns.Add(new DataColumn("EmpName", typeof(string)));
dt.Columns.Add(new DataColumn("DeptName", typeof(string)));
dt.Columns.Add(new DataColumn("EmpAddress", typeof(string)));
dt.Columns.Add(new DataColumn("EmpSalary", typeof(string)));
string Id = string.Empty;
string Name = string.Empty;
string DeptName = string.Empty;
string EmpAddress = string.Empty;
string EmpSalary = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = (GridViewRow)GridView1.Rows[i];
if (i != e.RowIndex)
{
Id = row.Cells[1].Text;
Name = row.Cells[2].Text;
DeptName = row.Cells[3].Text;
EmpAddress = row.Cells[4].Text;
EmpSalary = row.Cells[5].Text;
DataRow dr = dt.NewRow();
dr["EmpId"] = Id;
dr["EmpName"] = Name;
dr["DeptName"] = DeptName;
dr["EmpAddress"] = EmpAddress;
dr["EmpSalary"] = EmpSalary;
dt.Rows.Add(dr);
}
}
GridView1.EditIndex = -1;
GridView1.DataBind();
GridView1.DataSource = dt;
}
My add to row code is this
private void AddNewRecordRowToGrid()
{
// check view state is not null
if (ViewState["EmployeeDetails"] != null)
{
//get datatable from view state
DataTable dtCurrentTable = (DataTable)ViewState["EmployeeDetails"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//add each row into data table
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["EmpId"] = txtEmpId.Text;
drCurrentRow["EmpName"] = txtEmpName.Text;
drCurrentRow["DeptName"] = txtDeptName.Text;
drCurrentRow["EmpAddress"] = txtEmpAddress.Text;
drCurrentRow["EmpSalary"] = txtEmpSalary.Text;
}
//Remove initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//add created Rows into dataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Bind Gridview with latest Row
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
}
Since you load the employees after adding from your ViewState
DataTable dtCurrentTable = (DataTable)ViewState["EmployeeDetails"];
the deleted row wasn't deleted there. I would suggest to edit the DataTable in your ViewState
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (ViewState["EmployeeDetails"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["EmployeeDetails"];
dtCurrentTable.Rows.RemoveAt(e.RowIndex);
ViewState["EmployeeDetails"] = dtCurrentTable;
GridView1.EditIndex = -1;
GridView1.DataBind();
GridView1.DataSource = dtCurrentTable;
}
}
and
private void AddNewRecordRowToGrid()
{
if (ViewState["EmployeeDetails"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["EmployeeDetails"];
DataRow drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["EmpId"] = txtEmpId.Text;
drCurrentRow["EmpName"] = txtEmpName.Text;
drCurrentRow["DeptName"] = txtDeptName.Text;
drCurrentRow["EmpAddress"] = txtEmpAddress.Text;
drCurrentRow["EmpSalary"] = txtEmpSalary.Text;
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["EmployeeDetails"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}

I can't Add New Row after Deleting Row in Gridview ASP.net

I have a strange problem with my code
I can't add row because NullReferenceException in my gridview after delete a row.
My logic is when Add new row, i have the other function to SetPreviousData.
When I didn't delete a row, my SetPreviousData is don't raise any exception, but when after deleting a row and create new row, my SetPreviousData raise a exception that NullReferenceException.
This is my code for 'AddNewRow()'
private void AddNewRowToGrid()
{
if (ViewState["vsCurrent"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["vsCurrent"];
DataRow drNewRow = dtCurrentTable.NewRow();
drNewRow["SALES_SO_LITEM_ID"] = Convert.ToInt32(dtCurrentTable.Rows.Count.ToString()+"101");
drNewRow["ITEM_NAME"] = string.Empty;
drNewRow["QUANTITY"] = 0;
drNewRow["PRICE"] = 0;
dtCurrentTable.Rows.Add(drNewRow);
ViewState["vsCurrent"] = dtCurrentTable;
}
else
{
ViewState["vsCurrent"] = SetInitialRow();
}
BindDataGrid();
SetPreviousData(); //Set Previous Data on Postbacks
}
and this function for SetPreviousData
public void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["vsCurrent"] != null)
{
DataTable dt = (DataTable)ViewState["vsCurrent"];
if (dt.Rows.Count > 0)
{
int max_rowindex = gvDetailSales.Rows.Count - 1;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i].RowState != DataRowState.Deleted)
{
Label box1 = (Label)gvDetailSales.Rows[rowIndex].Cells[1].FindControl("lblItemName");
// raise exception because null
Label box2 = (Label)gvDetailSales.Rows[rowIndex].Cells[2].FindControl("lblQuantity");
Label box3 = (Label)gvDetailSales.Rows[rowIndex].Cells[3].FindControl("lblPrice");
box1.Text = dt.Rows[i]["ITEM_NAME"].ToString();
box2.Text = dt.Rows[i]["QUANTITY"].ToString();
box3.Text = dt.Rows[i]["PRICE"].ToString();
rowIndex++;
}
}
}
}
}
How I can handle it ? Thank You
======================EDITED================================================
This is my function for SetInitialRow
public DataTable SetInitialRow()
{
DataTable dtInitial = new DataTable();
DataRow drInitial = null;
dtInitial.Columns.Add(new DataColumn("SALES_SO_LITEM_ID", typeof(string)));
dtInitial.Columns.Add(new DataColumn("ITEM_NAME", typeof(string)));
dtInitial.Columns.Add(new DataColumn("QUANTITY", typeof(int)));
dtInitial.Columns.Add(new DataColumn("PRICE", typeof(float)));
drInitial = dtInitial.NewRow();
drInitial["SALES_SO_LITEM_ID"] = Convert.ToInt32(dtInitial.Rows.Count.ToString() + "101");
drInitial["ITEM_NAME"] = string.Empty;
drInitial["QUANTITY"] = 0;
drInitial["PRICE"] = 0.0;
dtInitial.Rows.Add(drInitial);
return dtInitial;
}
This is my function for BindDataGrid
public void BindDataGrid()
{
gvDetailSales.DataSource = ViewState["vsCurrent"] as DataTable;
gvDetailSales.DataBind();
}

the selectedindex and selectedvalue attributes are mutually exclusive exception?

protected void ddlbranchdate_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DataTable dtgetvalues = new DataTable();
//objRetailPL.date = Convert.ToDateTime(hdndate.Value);
objRetailPL.branchdate = ddlbranchdate.SelectedItem.ToString();
dtgetvalues = objRetailBAL.getbradisdate(objRetailPL);
foreach(GridViewRow row in gvMeatDispatch.Rows)
{
DataTable dtpr = new DataTable();
DropDownList ddl1 = (DropDownList)row.FindControl("ddlpartyname");
objRetailPL.branch = dtgetvalues.Rows[0]["branch"].ToString();
dtpr = objRetailBAL.getbran(objRetailPL);
ddl1.DataSource = dtpr;
ddl1.DataTextField = "partyname";
ddl1.DataValueField = "sno";
ddl1.DataBind();
ddl1.Items.Add(new ListItem("--Select--", "0"));
ddl1.SelectedIndex = ddl1.Items.Count - 1;
}
}
}
why i am getting this exception?..
i am using Dynamic Gridview and adding Rows Dynamically with the help of Button Control..
Outside i am declare another dropdown list ..if user selected some value from this Dropdownlist
then automatically bind the values to Dynamic Gridview ,Dropdown list values..
This is my Setprevious Data in Dynamic control Method..Here i called Dropdownlist selectedindexchanged event ..like..
private void SetPreviousData()
{
try
{
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++)
{
DropDownList ddlpname = (DropDownList)gvMeatDispatch.Rows[rowIndex].Cells[1].FindControl("ddlpartyname");
DropDownList ddlbt = (DropDownList)gvMeatDispatch.Rows[rowIndex].Cells[2].FindControl("ddlbirdtype");
TextBox txttotwt = (TextBox)gvMeatDispatch.Rows[rowIndex].Cells[3].FindControl("txttotwt");
TextBox txttransbirds1 = (TextBox)gvMeatDispatch.Rows[rowIndex].Cells[4].FindControl("txtrateforkg");
TextBox txtmort1 = (TextBox)gvMeatDispatch.Rows[rowIndex].Cells[5].FindControl("txtdcno");
// Dropdownlist selectedIndex Changed event
ddlbranchdate_SelectedIndexChanged(null, null);
ddlpname.SelectedValue = dt.Rows[i]["Col1"].ToString();
ddlbt.SelectedValue = dt.Rows[i]["Col2"].ToString();
txttotwt.Text = dt.Rows[i]["col3"].ToString();
txttransbirds1.Text = dt.Rows[i]["Col4"].ToString();
txtmort1.Text = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}

c# Grid View setting rows number back to 1

I have this code here :
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Question", typeof(string)));
dt.Columns.Add(new DataColumn("Answer", typeof(string)));
dr = dt.NewRow();
dr["Question"] = string.Empty;
dr["Answer"] = 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");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["Question"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Answer"] = box2.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");
box1.Text = dt.Rows[i]["Question"].ToString();
box2.Text = dt.Rows[i]["Answer"].ToString();
Session["Question1"] = box1.Text;
rowIndex++;
}
}
}
}
protected void btnAdd_Click1(object sender, EventArgs e)
{
AddNewRowToGrid();
}
And now i have another button call btnCreate . I click the add button to add rows in Grid View , means adding one row and so on every click . After i click create button , i want the rows number back to one , for now , the rows will be stuck at the number of times i click the add button until i refresh the page. I need the number of rows to be reseted to 1 after i have click on the create button .
You can direcly call SetInitialRow() method in your btnCreate click event, that means you are binding a single row to gridview which mean number of rows reseted to 1.
You can add this to the btnAdd_Click1 method:
dtCurrentTable.Rows(1).Selected = True
I have tried your same code and it works in mine.
Like this.
protected void Page_Load(object sender, EventArgs e)
{
SetInitialRow();
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Question", typeof(string)));
dt.Columns.Add(new DataColumn("Answer", typeof(string)));
dr = dt.NewRow();
dr["Question"] = string.Empty;
dr["Answer"] = 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[i].FindControl("TextBox1");
TextBox box2 = (TextBox)GridView1.Rows[i].FindControl("TextBox2");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["Question"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Answer"] = box2.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].FindControl("TextBox1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].FindControl("TextBox2");
box1.Text = dt.Rows[i]["Question"].ToString();
box2.Text = dt.Rows[i]["Answer"].ToString();
Session["Question1"] = box1.Text;
rowIndex++;
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void prevRow_Click(object sender, EventArgs e)
{
SetPreviousData();
}
I am sory sory if my answer is on wrong track depending on your requirement. Comment and queries are welcome. thank you

c# how do Ikeep my radio button selection after postback

This is how my gridview looks like :
Basically , I select "you" as the correct answer .
But after I click the "+" button , the selection of radio button got removed .
How do I keep my selection of radio button for every row of gridview?
This is my code:
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++;
}
}
}
}
Basically I need to keep the selection of radio button for every row I have created.
Consider changing the "+" button to trigger an event on the client side instead of posting to the server for a new row. You could then just loop through the collection when you post it to your "Save" event handler on the server.
Currently what seems to be happening is a postback from you hitting the "+" button. A postback would result in the clearing of those radio buttons. I see you're trying to retain the status via the ViewState but you're saving the checked status for the same ViewState property.
See the difference in the code below.
if (radiobtn1.Checked == true)
{
ViewState["RadioButtonStatus"] = radiobtn1.Checked;
}
if (radiobtn2.Checked == true)
{
ViewState["DifferentRadioButtonStatus"] = radiobtn2.Checked;
}
Here are some updates to your AddNewRow method. There's a lot of stuff going on here, this may be a little bit over engineered. Hope it helps you move towards the right direction.
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
var drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
// Updated from > 0 to > 1 since the first action you're taking is in GridView1.Rows[1] via the for loop below
if (dtCurrentTable.Rows.Count > 1)
{
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");
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++;
}
ViewState["CurrentTable"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
// Set Previous Data on Postbacks
SetPreviousData();
}

Categories

Resources