I am having a Gridview with 1 checkbox column and 3 other columns. To 1 colums I am adding values from a TextBox on ButtonClick.
I want that duplicate values should not displayed in the gridview for which I have added code in Rowdatabound.
The code works perfectly when paging is disabled but when paging is enabled code works only if a duplicate value is added to the same page but if the value being added is to the next page the value is accepted.
protected void GVRequest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//switch for first row
if (e.Row.RowIndex == 1)
{
GridViewRow Gprev = GVRequest.Rows[e.Row.RowIndex - 1];
if (Gprev.Cells[1].Text.Equals(e.Row.Cells[1].Text))
{
e.Row.Cells[1].Text = "";
e.Row.Visible = false;
}
}
//now continue with the rest of the rows
if (e.Row.RowIndex > 1)
{
//set reference to the row index and the current value
int intC = e.Row.RowIndex;
string lookfor = e.Row.Cells[1].Text;
//now loop back through checking previous entries for matches
do
{
GridViewRow Gprev = GVRequest.Rows[intC - 1];
if (Gprev.Cells[1].Text.Equals(e.Row.Cells[1].Text))
{
//e.Row.Cells[0].Text = "";
//e.Row.Cells[1].Text = "";
//e.Row.Cells[2].Text = "";
//e.Row.Cells[3].Text = "";
e.Row.Visible = false;
//Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('ID already added for processing');", true);
}
intC = intC - 1;
} while (intC > 0);
}
}
}
protected void GVRequest_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
//DataRow drCurrentRow = null;
GVRequest.PageIndex = e.NewPageIndex;
GVRequest.DataSource = dtCurrentTable;
//SetPreviousData();
//GVRequest.DataBind();
DataBind();
}
//Add new Row
private void AddNewRowToGrid()
{
if (ViewState["CurrentTable"] != null)
{
try
{
string RequestID = Request.QueryString["RequestID"];
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
const string SQLFileRetrievalReq = "SELECT DeptFileID, FileStatus, FileID, RequestID FROM FileInwardMaster WHERE (FileID = #FileID) AND (RequestID = #RequestID)";
SqlCommand cmdFileRetrievalReq = new SqlCommand(SQLFileRetrievalReq, conn);
cmdFileRetrievalReq.Parameters.Add("#RequestID", SqlDbType.VarChar);
cmdFileRetrievalReq.Parameters["#RequestID"].Value = RequestID;
cmdFileRetrievalReq.Parameters.Add("#FileID", SqlDbType.VarChar);
cmdFileRetrievalReq.Parameters["#FileID"].Value = TextBoxFileIds.Text.ToString();
conn.Open();
SqlDataReader reader = cmdFileRetrievalReq.ExecuteReader();
reader.Read();
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
drCurrentRow = dtCurrentTable.NewRow();
//drCurrentRow["SlNo"] = dtCurrentTable.Rows.Count + 1;
drCurrentRow["FileID"] = TextBoxFileIds.Text.ToUpper();
drCurrentRow["RequestID"] = RequestID;
drCurrentRow["DeptFileID"] = reader["DeptFileID"].ToString();
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
GVRequest.DataSource = dtCurrentTable;
GVRequest.DataBind();
}
catch
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('ID Entered/Scanned not valid for Request. Please Enter/Scan a valid ID to proceed');", true);
SetPreviousData();
//SetInitialRow();
//GVRequest.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
//Get Previous Data
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++)
{
dt.Rows[i]["FileID"].ToString();// = txtRcptHdNo.Text;
dt.Rows[i]["RequestID"].ToString();// = ddlRcptDtlsItem.SelectedItem.Text;
dt.Rows[i]["DeptFileID"].ToString();// = ddlRcptDtlsItem.SelectedItem.Text;
rowIndex++;
}
}
}
}
private void SetInitialRow()
{
string RequestID = Request.QueryString["RequestID"];
DataTable dt = new DataTable();
//DataRow dr = null;
dt.Columns.Add(new DataColumn("RequestID", typeof(string)));
dt.Columns.Add(new DataColumn("FileID", typeof(string)));
dt.Columns.Add(new DataColumn("DeptFileID", typeof(string)));
// dr = dt.NewRow();
// dr["RequestID"] = string.Empty;
//dr["FileID"] = string.Empty;
//dr["DeptFileID"] = string.Empty;
//dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
GVRequest.DataSource = dt;
GVRequest.DataBind();
}
protected void BtnAddFileID_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
//GenerateUniqueData(0);
TextBoxFileIds.Text = "";
}
Related
I am trying to use a checkbox control in gridview. Basically the user would enter an Item Description, the Quantity of the Item used, and if it has already been "Sold" out of inventory. The checkbox when checked would indicate the item was sold. Unchecked it can be null or no. I can store the value in the database as 1/2, true/false, yes/no. It doesn't matter.
I have tried using bit type, int, and varchar in my database. And have tried multiple ways of getting the value for the check in C# and can't seem to get it to work.
I've searched all over and have found examples on how to use it to save or delete multiple rows. But I need it to actually store a value in my db.
Here's code I've scavenged from other posts and almost have something working.
public partial class WebForm1 : System.Web.UI.Page
{
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);
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++)
{
TextBox itemDesc = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("txtItemDesc");
TextBox quantity = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txtQuantity");
CheckBox sold = (CheckBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("alreadySold");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = itemDesc.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = quantity.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = sold.Checked.ToString();
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 itemDesc = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("txtItemDesc");
TextBox quantity = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txtQuantity");
CheckBox sold = (CheckBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("alreadySold");
itemDesc.Text = dt.Rows[i]["Column1"].ToString();
quantity.Text = dt.Rows[i]["Column2"].ToString();
sold.Checked = dt.Rows[i]["Column3"].ToString().ToUpperInvariant() == "TRUE";
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Save(object sender, System.EventArgs e)
{
if (ViewState["CurrentTable"] != null)
{
DataTable dt = new DataTable();
dt = ViewState["CurrentTable"] as DataTable;
if (dt.Rows.Count > 0)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
SqlCommand cmd = null;
foreach (GridViewRow row in Gridview1.Rows)
{
cmd = new SqlCommand("INSERT INTO SampleTest (ItemDesc, Quantity, Sold) VALUES (#Column1, #Column2, #Column3)", con);
string itemDesc = (row.FindControl("txtItemDesc") as TextBox).Text;
string quantity = (row.FindControl("txtQuantity") as TextBox).Text;
CheckBox sold = (row.FindControl("alreadySold") as CheckBox);
if (sold == null)
{
sold.Checked = false;
}
else
{
sold.Checked = true;
}
cmd.Parameters.AddWithValue("#Column1", itemDesc);
cmd.Parameters.AddWithValue("#Column2", quantity);
cmd.Parameters.AddWithValue("#Column3", sold);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
//cmd = new SqlCommand("SELECT Column1,Column2,Column3 FROM SampleTest", con);
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//DataTable dt1 = new DataTable();
//da.Fill(dt1);
//this.gvSample.DataSource = dt1;
//this.gvSample.DataBind();
}
}
}
}
}
In your save, instead of CheckBox sold try something like:
bool sold = (row.FindControl("alreadySold") as CheckBox)?.Checked ?? false;
So a little explanation on the above:
as CheckBox can return null.
the '?' in CheckBox)? is a null conditional check that will prevent a null exception being thrown if it is null.
the '??' is saying that if the code preceding that is null, instead of assigning null, it assigns 'false'. Now if the code preceding the ?? is not null, then it will set the bool variable value to whatever .Checked actually is (true or false).
Now if your DB allows NULLs in that column and you are fine with that, you can also do:
bool? sold = (row.FindControl("alreadySold") as CheckBox)?.Checked;
^ bool? is a what is called a Nullable value type. Value types can't be null, but nullable value types wrap around a value type and allow it be null.
I'm an idiot. Thank you B.O.B. for explaining what was happening with the null value and the checkbox control. It really helped me understand what was happening. The reason the other things didn't work is because I had a type-o on the checkbox control on the HTML page. Once I fixed that everything works perfect.
Adding data in datatable from dropdown and displaying it in gridview. Then I am deleting a row and maintaining the ViewState but after deleting one row and mapping my values again I get the earlier state of the table in the gridview with duplicated records.
Here's the code:
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
//dt = new DataTable("tblTest");
//dt = ViewState["updatedtbl"] as DataTable;
DataColumn dc1 = new DataColumn();
dc1.DataType = typeof(String);
dc1.ColumnName = "A";
DataColumn dc2 = new DataColumn();
dc2.DataType = typeof(String);
dc2.ColumnName = "B";
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
//ViewState["dt"] = dt;
}
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
DataTable dt = new DataTable();
ExcelPackage package = new ExcelPackage(FileUpload1.FileContent);
dt = package.ToDataTable();
DropDownList1.Items.Clear();
for (int i = 0; i < dt.Columns.Count; i++)
{
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName));
}
}
}
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["A"] += DropDownList1.SelectedItem.Value + "|";
Session["B"] += DropDownList2.SelectedItem.Value + "|";
CreateTable();
}
public void CreateTable()
{
string[] sa = Session["A"].ToString().Split('|');
string[] sb = Session["B"].ToString().Split('|');
int recordnum = sa.Length;
for (int j = 0; j < recordnum - 1; j++)
{
DataRow dr = dt.NewRow();
dr["A"] = sa[j].ToString();
dr["B"] = sb[j].ToString();
dt.Rows.Add(dr);
}
ViewState["tbl"] = dt;
BindGrid();
}
protected void BindGrid()
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dx = ViewState["tbl"] as DataTable;
//DataTable dx = dt;
if (dx.Rows.Count > 0)
{
dx.Rows[e.RowIndex].Delete();
dx.AcceptChanges();
GridView2.DataSource = dx;
GridView2.DataBind();
ViewState["updatedtbl"] = dx;
}
else //To check which portion of code is being executed
{
Label1.Text = "Deleted";
Label2.Text = dx.Rows.Count.ToString();
}
}
In delete event you are reassigning the updated datatable to different viewstate with name updatedtbl. You should assign it to ViewState["tbl"].
if(dx.Rows.Count > 0)
{
dx.Rows[e.RowIndex].Delete();
dx.AcceptChanges();
GridView2.DataSource = dx;
GridView2.DataBind();
//ViewState["updatedtbl"] = dx; <<---- pay attention here
ViewState["tbl"] = dx; <<---- pay attention here
}
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.