I have created an editable gridview and I wan to add rows as many rows as I want at runtime. It is working fine but I'm only able to add 9 rows after that I get a Index out of bound exception, where as I'm not setting the limit anywhere in my code.
private void SetInitialRow()
{
DataTable dtable = new DataTable();
DataRow dr = null;
dtable.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dtable.Columns.Add(new DataColumn("Column1", typeof(string)));
dtable.Columns.Add(new DataColumn("Column2", typeof(string)));
dtable.Columns.Add(new DataColumn("Column3", typeof(string)));
dtable.Columns.Add(new DataColumn("Column4", typeof(string)));
dtable.Columns.Add(new DataColumn("Column5", typeof(string)));
dtable.Columns.Add(new DataColumn("Column6", typeof(string)));
dtable.Columns.Add(new DataColumn("Column7", typeof(string)));
dtable.Columns.Add(new DataColumn("Column8", typeof(string)));
dr = dtable.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dr["Column5"] = string.Empty;
dr["Column6"] = string.Empty;
dr["Column7"] = string.Empty;
dr["Column8"] = string.Empty;
dtable.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dtable;
GridView1.DataSource = dtable;
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 Gtb_ffcode = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("Gtb_ffcode");
TextBox Gtb_terr = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("Gtb_terr");
DropDownList GddlTeam = (DropDownList)GridView1.Rows[rowIndex].Cells[3].FindControl("GddlTeam");
TextBox Gtb_fromdt = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("Gtb_fromdt");
TextBox Gtb_todt = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("Gtb_todt");
DropDownList Gddl_desg = (DropDownList)GridView1.Rows[rowIndex].Cells[6].FindControl("Gddl_desg");
DropDownList Gddl_role = (DropDownList)GridView1.Rows[rowIndex].Cells[7].FindControl("Gddl_role");
TextBox Gtb_manager = (TextBox)GridView1.Rows[rowIndex].Cells[8].FindControl("Gtb_manager");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = Gtb_ffcode.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = Gtb_terr.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = GddlTeam.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = Gtb_fromdt.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = Gtb_todt.Text;
dtCurrentTable.Rows[i - 1]["Column6"] = Gddl_desg.Text;
dtCurrentTable.Rows[i - 1]["Column7"] = Gddl_role.Text;
dtCurrentTable.Rows[i - 1]["Column8"] = Gtb_manager.Text;
drCurrentRow["Column1"] = Gtb_ffcode.Text = maxcode; // write ff code to the new generating row
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 Gtb_ffcode = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("Gtb_ffcode");
TextBox Gtb_terr = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("Gtb_terr");
DropDownList GddlTeam = (DropDownList)GridView1.Rows[rowIndex].Cells[3].FindControl("GddlTeam");
TextBox Gtb_fromdt = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("Gtb_fromdt");
TextBox Gtb_todt = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("Gtb_todt");
DropDownList Gddl_desg = (DropDownList)GridView1.Rows[rowIndex].Cells[6].FindControl("Gddl_desg");
DropDownList Gddl_role = (DropDownList)GridView1.Rows[rowIndex].Cells[7].FindControl("Gddl_role");
TextBox Gtb_manager = (TextBox)GridView1.Rows[rowIndex].Cells[8].FindControl("Gtb_manager");
Gtb_ffcode.Text = dt.Rows[i]["Column1"].ToString();
Gtb_terr.Text = dt.Rows[i]["Column2"].ToString();
GddlTeam.Text = dt.Rows[i]["Column3"].ToString();
Gtb_fromdt.Text = dt.Rows[i]["Column4"].ToString();
Gtb_todt.Text = dt.Rows[i]["Column5"].ToString();
Gddl_desg.Text = dt.Rows[i]["Column6"].ToString();
Gddl_role.Text = dt.Rows[i]["Column7"].ToString();
Gtb_manager.Text = dt.Rows[i]["Column8"].ToString();
rowIndex++;
}
}
}
}
Related
I have a table opbal1 in database with fields sno, voc, date, ledcode, type, amt ,part.
Till I save the data it is ok but when I am editing the data getting the error
The parameterized query '(#voc nvarchar(11),#date nvarchar(10),#ledcode nvarchar(4000),#t'
expects the parameter '#ledcode', which was not supplied
My code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FirstGrid();
}
}
private void FirstGrid()
{
string sno = Request.QueryString["sno"];
Response.Write(sno);
if (sno == null)
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("0", typeof(string)));
dt.Columns.Add(new DataColumn("1", typeof(string)));
dt.Columns.Add(new DataColumn("2", typeof(string)));
dt.Columns.Add(new DataColumn("3", typeof(string)));
dt.Columns.Add(new DataColumn("4", typeof(string)));
dt.Columns.Add(new DataColumn("5", typeof(string)));
dt.Columns.Add(new DataColumn("6", typeof(string)));
dt.Columns.Add(new DataColumn("7", typeof(string)));
dr = dt.NewRow();
dr[0] = string.Empty;
dr[1] = string.Empty;
dr[2] = string.Empty;
dr[3] = string.Empty;
dr[4] = string.Empty;
dr[5] = string.Empty;
dr[6] = string.Empty;
dr[7] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
grvOpbal.DataSource = dt;
grvOpbal.DataBind();
}
else
{
Response.Write(Session["flag"]);
if (Session["flag"] == "2" || Session["flag"] == "3")
{
conn.Open();
hdnFlag.Value = Session["flag"].ToString();
btnSave.Enabled = true;
SqlCommand cmd = new SqlCommand("select * from opbal1 where sno=#sno", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
cmd.Parameters.AddWithValue("#sno", sno);
DataTable dt = new DataTable();
da.Fill(dt);
grvOpbal.DataSource = dt;
ViewState["CurrentTable"] = dt;
grvOpbal.DataBind();
int i = 0;
foreach (DataRow row in dt.Rows)
{
Label lblSno = (Label)grvOpbal.Rows[i].Cells[0].FindControl("lblSno");
Label lblSrNumber = (Label)grvOpbal.Rows[i].Cells[1].FindControl("lblSrNumber");
DropDownList ddlLedCode = (DropDownList)grvOpbal.Rows[i].Cells[2].FindControl("ddlLedCode");
TextBox txtType = (TextBox)grvOpbal.Rows[i].Cells[3].FindControl("txtType");
TextBox txtAmt = (TextBox)grvOpbal.Rows[i].Cells[4].FindControl("txtAmt");
TextBox txtPart = (TextBox)grvOpbal.Rows[i].Cells[5].FindControl("txtPart");
TextBox txtVoc = (TextBox)grvOpbal.Rows[i].Cells[6].FindControl("txtVoc");
TextBox txtDate = (TextBox)grvOpbal.Rows[i].Cells[7].FindControl("txtDate");
lblSrNumber.Text = Convert.ToInt32(i + 1).ToString();
lblSno.Text = row[0].ToString();
txtVoc.Text = row[1].ToString();
txtDate.Text = row[2].ToString();
ddlLedCode.SelectedValue = row[3].ToString();
txtType.Text = row[4].ToString();
if (txtType.Text == "D" || txtType.Text == "d")
{
txtAmt.BackColor = System.Drawing.Color.Red;
}
else
{
txtAmt.BackColor = System.Drawing.Color.Blue;
}
txtAmt.Text = row[5].ToString();
txtPart.Text = row[6].ToString();
i++;
}
}
}
}
private void SetRowData()
{
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++)
{
Label lblSno = (Label)grvOpbal.Rows[rowIndex].Cells[1].FindControl("lblSno");
Label lblSrNumber = (Label)grvOpbal.Rows[rowIndex].Cells[2].FindControl("lblSrNumber");
DropDownList ddlLedCode = (DropDownList)grvOpbal.Rows[rowIndex].Cells[3].FindControl("ddlLedCode");
TextBox txtType = (TextBox)grvOpbal.Rows[rowIndex].Cells[4].FindControl("txtType");
TextBox txtAmt = (TextBox)grvOpbal.Rows[rowIndex].Cells[5].FindControl("txtAmt");
TextBox txtPart = (TextBox)grvOpbal.Rows[rowIndex].Cells[6].FindControl("txtPart");
TextBox txtVoc = (TextBox)grvOpbal.Rows[rowIndex].Cells[7].FindControl("txtVoc");
TextBox txtDate = (TextBox)grvOpbal.Rows[rowIndex].Cells[8].FindControl("txtDate");
if (txtType.Text == "D")
{
//txtType.Attributes.Add("OnFocus", "return OnFocus()");
txtAmt.BackColor = System.Drawing.Color.Red;
}
else
{
txtAmt.BackColor = System.Drawing.Color.Blue;
}
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1][0] = lblSno.Text;
dtCurrentTable.Rows[i - 1][1] = txtVoc.Text;
dtCurrentTable.Rows[i - 1][2] = txtDate.Text;
dtCurrentTable.Rows[i - 1][3] = ddlLedCode.SelectedValue;
dtCurrentTable.Rows[i - 1][4] = txtType.Text;
dtCurrentTable.Rows[i - 1][5] = txtAmt.Text;
dtCurrentTable.Rows[i - 1][6] = txtPart.Text;
// dtCurrentTable.Rows[i - 1][7] =
lblSrNumber.Text = i.ToString();
rowIndex++;
}
ViewState["CurrentTable"] = dtCurrentTable;
}
}
else
{
Response.Write("Viewstate is null");
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
SetRowData();
conn.Open();
DataTable table = ViewState["CurrentTable"] as DataTable;
if (table != null)
{
foreach (DataRow row in table.Rows)
{
int j = 1;
string lblSno = row.ItemArray[0] as string;
string txtVoc = row.ItemArray[1] as string;
string txtDate = row.ItemArray[2] as string;
//string lblSrNumber = row.ItemArray[1] as string;
string ddlLedCode = row.ItemArray[3] as string;
string txtType = row.ItemArray[4] as string;
string txtAmt = row.ItemArray[5] as string;
string txtPart = row.ItemArray[6] as string;
string lblSrNumber = j.ToString();
j++;
if (hdnFlag.Value == "1")
{
string sql1="insert into opbal1 values(#voc,#date,#ledcode,#type,#amt,#part)";
SqlCommand cmd2 = new SqlCommand(sql1, conn);
cmd2.Parameters.AddWithValue("#voc", mmvoc);
cmd2.Parameters.AddWithValue("#date", today);
cmd2.Parameters.AddWithValue("#ledcode", ddlLedCode);
cmd2.Parameters.AddWithValue("#type", txtType);
cmd2.Parameters.AddWithValue("#amt", txtAmt);
cmd2.Parameters.AddWithValue("#part", "opbal");
cmd2.ExecuteNonQuery();
}
else if (hdnFlag.Value == "2")
{
string today = DateTime.Now.ToString("yyyy-dd-M");
string sql = "update opbal1 set voc=#voc,date=#date,";
sql += "ledcode=#ledcode,type=#type,amt=#amt,part=#part where sno=#sno";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#voc", txtVoc);
cmd.Parameters.AddWithValue("#date", today);
cmd.Parameters.AddWithValue("#ledcode", ddlLedCode);
cmd.Parameters.AddWithValue("#type", txtType);
cmd.Parameters.AddWithValue("#amt",txtAmt);
cmd.Parameters.AddWithValue("#part", "opbal");
cmd.Parameters.AddWithValue("#sno", lblSno);
cmd.ExecuteNonQuery();
btnSave.Enabled = false;
}
}
}
}
I think your problem is probably the value of ddlLedCode is null, because null is not treated as valid value, you need to pass DBNull.Value in that case:-
if(ddlLedCode != null)
cmd.Parameters.AddWithValue("#ledcode", ddlLedCode);
else
cmd.Parameters.AddWithValue("#ledcode", DBNull.Value);
Also, Please read can we stop using AddWithValue?
So, this will be better:-
if (ddlLedCode != null)
cmd.Parameters.Add("#ledcode", SqlDbType.NVarChar).Value = ddlLedCode;
else
cmd.Parameters.Add("#ledcode", SqlDbType.NVarChar).Value = DBNull.Value;
foreach (DataRow row in table.Rows)
{
int j = 1;
string lblSno = row[0].ToString();
string txtVoc = row[1].ToString();
string txtDate = row[2].ToString();
//string lblSrNumber = row.ItemArray[1] as string;
string ddlLedCode = row[3].ToString();
string txtType = row[4].ToString();
string txtAmt = row[5].ToString();
string txtPart = row[6].ToString();
}
Instead of using "row.ItemArray[1] as string" I have used the above statements so I am not getting the error
I have a Grid view containing 3 drop down lists and 3 text boxes each and a button. my drop down lists are populating data from data base. When i click on the button to add new row after filling the initial row. it sets the first row values fine and adds a new row. but the new row has no items in drop down lists this is my problem. secondly when i click the button again for adding third row it even looses the value of first row filled and same problem comes with first row that there are no items in drop down lists.
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)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dt.Columns.Add(new DataColumn("Column4", typeof(string)));
dt.Columns.Add(new DataColumn("Column5", typeof(string)));
dt.Columns.Add(new DataColumn("Column6", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dr["Column4"] = string.Empty;
dr["Column5"] = string.Empty;
dr["Column6"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
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 and dropdown lists values
DropDownList list1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = list1.SelectedItem.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = list2.SelectedItem.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = list3.SelectedItem.Text;
dtCurrentTable.Rows[i - 1]["Column6"] = box3.Text;
Session["list1"] = dtCurrentTable.Rows[i - 1]["Column1"];
Session["list2"] = dtCurrentTable.Rows[i - 1]["Column2"];
Session["list3"] = dtCurrentTable.Rows[i - 1]["Column5"];
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();
}
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++)
{
DropDownList list1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("TextBox3");
list1.DataSource = bindddl();
list1.DataValueField = "Item_name";
list1.DataTextField = "Item_name";
list1.DataBind();
list1.Items.Insert(0, new ListItem("--Select--", "0"));
list2.DataSource = binddd2();
list2.DataValueField = "Sub_item";
list2.DataTextField = "Sub_item";
list2.DataBind();
list2.Items.Insert(0, new ListItem("--Select--", "0"));
list3.Items.Insert(0, new ListItem("--Select--", "0"));
list3.Items.Insert(1, new ListItem("Yes", "1"));
list3.Items.Insert(2, new ListItem("No", "2"));
box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
box3.Text = dt.Rows[i]["Column6"].ToString();
list1.Text = Session["list1"].ToString();
list2.Text = Session["list2"].ToString();
box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
list3.Text = Session["list3"].ToString();
box3.Text = dt.Rows[i]["Column6"].ToString();
// Response.Write(Session["list1"]);
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
Fillcombo();
Fillcombo1();
Fillcombo2();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
Fillcombo();
Fillcombo1();
Fillcombo2();
}
Fillcombo,Fillcombo1 are functions which are populating Drop down lists 1,2 through data base Fillcombo2 is populating it has two items yes' and 'no'.
My Fillcombo functions are like this
try
{
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{conn.Open();
SqlCommand cmdstr = new SqlCommand("SELECT [Sub_item] FROM [ADS].[dbo].[Accounts_heads_data]", conn);
// SqlCommand cmdstr = new SqlCommand("SELECT * FROM [ADS].[dbo].[Accounts_heads_data] ", conn);
SqlDataAdapter da2 = new SqlDataAdapter(cmdstr);
DataSet ds2 = new DataSet();
da2.Fill(ds2);
DropDownList DropDownList2 = (DropDownList)Gridview1.Rows[0].FindControl("DropDownList2");
DropDownList2.DataValueField = ds2.Tables[0].Columns["Sub_item"].ToString();
DropDownList2.DataTextField = ds2.Tables[0].Columns["Sub_item"].ToString();
DropDownList2.DataSource = ds2.Tables[0];
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("--Select--", "0"));
ViewState["fc1"] = ds2;
conn.Close();
}
}
catch (Exception ex)
{
Label1.Visible = true;
}
}
check by comenting
SetPreviousData(); line from
AddNewRowToGrid function
OR
in AddNewRowToGrid function only set data for new row and call SetPreviousData(); function in first row of AddNewRowToGrid function.
I compiled your code with some test data and changed the code a bit. Try following and see.
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;
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 0; i < dtCurrentTable.Rows.Count-1; i++)
{
DropDownList list1 = (DropDownList)Gridview1.Rows[i].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[i].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[i].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[6].FindControl("TextBox3");
dtCurrentTable.Rows[i]["Column1"] = list1.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column2"] = list2.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column3"] = box1.Text;
dtCurrentTable.Rows[i]["Column4"] = box2.Text;
dtCurrentTable.Rows[i]["Column5"] = list3.SelectedItem.Text;
dtCurrentTable.Rows[i]["Column6"] = box3.Text;
}
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
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++)
{
DropDownList list1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
DropDownList list2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DropDownList2");
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox2");
DropDownList list3 = (DropDownList)Gridview1.Rows[rowIndex].Cells[5].FindControl("DropDownList3");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[6].FindControl("TextBox3");
Fillcombo();
Fillcombo1();
Fillcombo2();
box1.Text = dt.Rows[i]["Column3"].ToString();
box2.Text = dt.Rows[i]["Column4"].ToString();
box3.Text = dt.Rows[i]["Column6"].ToString();
if (i < dt.Rows.Count - 1)
{
list1.ClearSelection();
list1.Items.FindByText(dt.Rows[i]["Column1"].ToString()).Selected = true;
list2.ClearSelection();
list2.Items.FindByText(dt.Rows[i]["Column2"].ToString()).Selected = true;
list3.ClearSelection();
list3.Items.FindByText(dt.Rows[i]["Column5"].ToString()).Selected = true;
}
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
I am able to add a row dynamically in a GridView through the following code but I need to do the same to be captured and displayed in Application every time when I open the application with the records I have added previously in the GridView.
Any Ideas??
Coding:
![enter image description here][1] protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
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)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
dr = dt.NewRow();
//Store the DataTable in ViewState
// ViewState["CurrentTable"] = dt;
Application["CurrentTable"]=dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
//if (ViewState["CurrentTable"] != null)
if (Application["CurrentTable"] != null)
{
//DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataTable dtCurrentTable1 = (DataTable)Application["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable1.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable1.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 = dtCurrentTable1.NewRow();
drCurrentRow["RowNumber"] = i + 1;
/*dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;*/
dtCurrentTable1.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable1.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable1.Rows[i - 1]["Column3"] = box3.Text;
rowIndex++;
}
dtCurrentTable1.Rows.Add(drCurrentRow);
//ViewState["CurrentTable"] = dtCurrentTable;
Application["CurrentTable"] = dtCurrentTable1;
Gridview1.DataSource = dtCurrentTable1;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
//if (ViewState["CurrentTable"] != null)
if (Application["CurrentTable"] != null)
{
//DataTable dt = (DataTable)ViewState["CurrentTable"];
DataTable dt1 = (DataTable)Application["CurrentTable"];
if (dt1.Rows.Count > 0)
{
for (int i = 0; i < dt1.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");
/*box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();*/
box1.Text = dt1.Rows[i]["Column1"].ToString();
box2.Text = dt1.Rows[i]["Column2"].ToString();
box3.Text = dt1.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
}
Since in your question you are talking about when the application is opened, what you will need to do is have a method to save the data in the grid view somewhere, i.e. Database, Text File etc.
This is because the Application variable is lost when the application is closed, so to re-open at the last point you will need to read the data you saved either in a Database or a Text file and re-create the DataTable object from that.
I have a page that dynamically creates gridviews on button click which that works fine. And along with it creating a grid, on the top of the grid there is a linkbutton to delete it. Now, what i am trying to accomplish is that when i delete one of the grids it will delete the grid from the page and resync the numbers. Meaning, lets say i have the following:
Grid1
Grid2
Grid3
Grid4
If i decide to delete Grid3, what actually happens is this:
Grid1
Grid2
Grid4
And then if i click something on the page for it to reload or something, then it will resync the numbers correctly:
Grid1
Grid2
Grid3
I have no idea why its doing that and why it doesn't do it this way in the first place. Can someone please help me with this?
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
string ctrlname = this.Page.Request.Params.Get("__EVENTTARGET");
if (Session["Tables"] == null)
{
Session.Add("Tables", 1);
DataTable dt = GetTable();
Session.Add(Session["Tables"].ToString(), dt);
GridView gv = new GridView();
gv.ID = "Grid-" + Session["Tables"].ToString();
gv.DataSource = dt;
gv.DataBind();
LinkButton lb = new LinkButton();
lb.ID = "Delete-Grid-" + Session["Tables"].ToString();
lb.Text = "Delete Grid " + Session["Tables"].ToString();
lb.Click += new EventHandler(DeleteGrid);
PlaceHolder1.Controls.Add(lb);
PlaceHolder1.Controls.Add(gv);
}
if (IsPostBack)
{
PlaceHolder1.Controls.Clear();
int next = (int)Session["Tables"];
for (int i = 1; i <= (int)Session["Tables"]; i++)
{
GridView gv = new GridView();
gv.ID = "Grid-" + i.ToString();
gv.DataSource = (DataTable)Session[i];
gv.DataBind();
LinkButton lb = new LinkButton();
lb.ID = "Delete-Grid-" + i.ToString();
lb.Text = "Delete Grid " + i.ToString();
lb.Click += new EventHandler(DeleteGrid);
PlaceHolder1.Controls.Add(lb);
PlaceHolder1.Controls.Add(gv);
}
if (ctrlname == "Button1")
{
next = next + 1;
Session["Tables"] = next;
DataTable dt = GetTable();
Session.Add(Session["Tables"].ToString(), dt);
GridView gv = new GridView();
gv.ID = "Grid-" + next.ToString();
gv.DataSource = (DataTable)Session[next];
gv.DataBind();
LinkButton lb = new LinkButton();
lb.ID = "Delete-Grid-" + next.ToString();
lb.Text = "Delete Grid " + next.ToString();
lb.Click += new EventHandler(DeleteGrid);
PlaceHolder1.Controls.Add(lb);
PlaceHolder1.Controls.Add(gv);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void DeleteGrid(object sender, EventArgs e)
{
LinkButton gridLink = (LinkButton)sender;
String gridNum = gridLink.ID.ToString().Split('-').Last();
GridView grid = (GridView)this.Page.FindControl("Grid-" + gridNum);
LinkButton lbd = (LinkButton)this.Page.FindControl("Delete-Grid-" + gridNum);
PlaceHolder1.Controls.Remove(grid);
PlaceHolder1.Controls.Remove(lbd);
int next = (int)Session["Tables"];
next = next - 1;
Session.Add("Tables", next);
Session.Remove(gridNum);
}
public DataTable GetTable()
{
//
// Here we create a DataTable with a few columns.
//
// Create Datatable to store all colums
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Size", typeof(string)));
dt.Columns.Add(new DataColumn("Description", typeof(string)));
dt.Columns.Add(new DataColumn("Quantity", typeof(string)));
dt.Columns.Add(new DataColumn("Unit", typeof(string)));
dt.Columns.Add(new DataColumn("Duration", typeof(string)));
dt.Columns.Add(new DataColumn("DurationType", typeof(string)));
dt.Columns.Add(new DataColumn("Amount", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Size"] = string.Empty;
dr["Description"] = string.Empty;
dr["Quantity"] = string.Empty;
dr["Unit"] = string.Empty;
dr["Duration"] = string.Empty;
dr["DurationType"] = string.Empty;
dr["Amount"] = string.Empty;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["RowNumber"] = 2;
dr["Size"] = string.Empty;
dr["Description"] = string.Empty;
dr["Quantity"] = string.Empty;
dr["Unit"] = string.Empty;
dr["Duration"] = string.Empty;
dr["DurationType"] = string.Empty;
dr["Amount"] = string.Empty;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["RowNumber"] = 3;
dr["Size"] = string.Empty;
dr["Description"] = string.Empty;
dr["Quantity"] = string.Empty;
dr["Unit"] = string.Empty;
dr["Duration"] = string.Empty;
dr["DurationType"] = string.Empty;
dr["Amount"] = string.Empty;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["RowNumber"] = 4;
dr["Size"] = string.Empty;
dr["Description"] = string.Empty;
dr["Quantity"] = string.Empty;
dr["Unit"] = string.Empty;
dr["Duration"] = string.Empty;
dr["DurationType"] = string.Empty;
dr["Amount"] = string.Empty;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["RowNumber"] = 5;
dr["Size"] = string.Empty;
dr["Description"] = string.Empty;
dr["Quantity"] = string.Empty;
dr["Unit"] = string.Empty;
dr["Duration"] = string.Empty;
dr["DurationType"] = string.Empty;
dr["Amount"] = string.Empty;
dt.Rows.Add(dr);
return dt;
}
}
you need to know the life cycle of an asp.net page first.
please refer to this article...
in your case, the delete even is firing after page load event.
therefore the sync is happening before the row is deleted.
may be you need to put the sync code in another method and call it after deletion...
i have a grid view that , user will have to type something in the textboxes and wadever the user type will be inserted into the database , i have this 2 problem or issues whereby , everytime i click the "+" button ( adds news row ) , one of the textbox of the previous row data will be removed .. And the radiobutton selected will be removed as well. Heres is the screenshot what the problem is :
After clicking the " + " button , it will turn to be like this :
This is my code behind :
private void AddNewRowToGrid()
{
int rowIndex = 0;
CheckBox chkbox1 = (CheckBox)GridView1.Rows[rowIndex].Cells[2].FindControl("CheckBox1");
CheckBox chkbox2 = (CheckBox)GridView1.Rows[rowIndex].Cells[2].FindControl("CheckBox2");
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[2].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["Question"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Hints"] = 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 SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Question", typeof(string)));
dt.Columns.Add(new DataColumn("Hints", typeof(string)));
dr = dt.NewRow();
dr["Question"] = string.Empty;
dr["Hints"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
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[2].FindControl("TextBox3");
//Setting previous text to the respective textboxes based on columns.
box1.Text = dt.Rows[i]["Question"].ToString();
box2.Text = dt.Rows[i]["Hints"].ToString();
box3.Text = dt.Rows[i]["Hints"].ToString();
Session["Question1"] = box1.Text;
rowIndex++;
}
}
}
}
I can easily do this when only there is one textbox on each columns .. but now there is 2 textboxes on each columns ... because i can only append text to the textboxes based on columns names ... Also , how do i maintain my radiobutton help is appreciated , thanks !
private void AddNewRowToGrid()
{
int rowIndex = 0;
CheckBox chkbox1 = (CheckBox)GridView1.Rows[rowIndex].Cells[2].FindControl("CheckBox1");
CheckBox chkbox2 = (CheckBox)GridView1.Rows[rowIndex].Cells[2].FindControl("CheckBox2");
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[2].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["Question"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Hints"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Hints1"] = 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 SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("Question", typeof(string)));
dt.Columns.Add(new DataColumn("Hints", typeof(string)));
dt.Columns.Add(new DataColumn("Hints1", typeof(string)));
dr = dt.NewRow();
dr["Question"] = string.Empty;
dr["Hints"] = string.Empty;
dr["Hints1"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
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[2].FindControl("TextBox3");
//Setting previous text to the respective textboxes based on columns.
box1.Text = dt.Rows[i]["Question"].ToString();
box2.Text = dt.Rows[i]["Hints"].ToString();
box3.Text = dt.Rows[i]["Hints1"].ToString();
Session["Question1"] = box1.Text;
rowIndex++;
}
}
}
}
I just added another column rest of code was already working fine.