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
}
Related
I am Not getting text field values into grid view. Only row increases but I do not get the text.
This is the code that I have for the purpose.
DataTable dt1 = new DataTable();
bool flag = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridVIEWData();
Gridview1.DataSource = dt1;
Gridview1.DataBind();
}
}
protected void gobtn_Click(object sender, EventArgs e)
{
if (Session["dtInSession"] != null)
dt1 = (DataTable)Session["dtInSession"];
DataRow dr = dt1.NewRow();
dr["Product"] = DropDownList1.SelectedItem;
dr["Size"] = DropDownList2.SelectedItem;
dr["Case"] = casetxt.Text;
dr["Weight"] = TextBox1.Text;
dr["Price"] = TextBox2.Text;
dt1.Rows.Add(dr);
Session["dtInSession"] = dt1;
Gridview1.DataSource = dt1;
Gridview1.DataBind();
}
private void gridVIEWData()
{
dt1.Columns.Add("Product", typeof(string));
dt1.Columns.Add("Size", typeof(string));
dt1.Columns.Add("Case", typeof(string));
dt1.Columns.Add("Weight", typeof(string));
dt1.Columns.Add("Price", typeof(string));
Session["dtInSession"] = dt1;
}
Please Can any one help me
**I hope you looking for something like this**
protected void BindGridview1()
{
DataTable dtt = new DataTable();
DataTable dt = (DataTable)Session["od"];
dtt.Columns.Add("BookingNO", typeof(string));
dtt.Columns.Add("ItemName", typeof(string));
dtt.Columns.Add("Size", typeof(string));
dtt.Columns.Add("Unit", typeof(string));
dtt.Columns.Add("Price", typeof(string));
dtt.Columns.Add("PendingQty", typeof(string));
for (int i = 0; i < dtt.Rows.Count; i++)
{
DataRow dr = dtt.NewRow();
dr["BookingNO"] = string.Empty;
dr["ItemName"] = string.Empty;
dr["Size"] = string.Empty;
dr["Unit"] = string.Empty;
dr["Price"] = string.Empty;
dr["PendingQty"] = string.Empty;
dtt.Rows.Add(dr);
}
dtt = dt;
gvDetails.DataSource = dtt;
gvDetails.DataBind();
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
TextBox BookingNO = (TextBox)gvDetails.Rows[i].FindControl("BookingNO");
TextBox ItemName = (TextBox)gvDetails.Rows[i].FindControl("ItemName");
TextBox Size = (TextBox)gvDetails.Rows[i].FindControl("Size");
TextBox Unit = (TextBox)gvDetails.Rows[i].FindControl("Unit");
TextBox Price = (TextBox)gvDetails.Rows[i].FindControl("Price");
//TextBox DueDate = (TextBox)gvDetails.Rows[i].FindControl("DueDate");
TextBox PendingQty = (TextBox)gvDetails.Rows[i].FindControl("PendingQty");
BookingNO.Text = Session["BookingNO1"].ToString();
ItemName.Text = dt.Rows[i]["ItemName"].ToString();
Size.Text = dt.Rows[i]["Size"].ToString();
Unit.Text = dt.Rows[i]["Unit"].ToString();
Price.Text = dt.Rows[i]["Price"].ToString();
//DueDate.Text = dt.Rows[i]["DueDate"].ToString();
PendingQty.Text = dt.Rows[i]["PendingQty"].ToString();
}
}
I have a form with 4textboxes + datagridview with 11columns.
Have from here a method to save datagridview this work fine, but is it possible to improve it so i can save not only the datagridview values, but the textboxes too??(then load too.)
thank you
Or is there something others that can be used for this?
private DataTable GetDataTableFromDGV(DataGridView dataGridView1)
{
var dt = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
if (column.Visible)
{
dt.Columns.Add();
}
}
object[] cellValues = new object[dataGridView1.Columns.Count];
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
private void SaveXML(object sender, EventArgs e)
{
//Savefile dialog for save CSV file
SaveFileDialog savefile = new SaveFileDialog();
savefile.FileName = tbOrderNr.Text + " - " + tbCustommer.Text + ".xml";
savefile.Filter = "xml files (*.xml)|*.xml";
if (savefile.ShowDialog() == DialogResult.OK)
{
DataTable dT = GetDataTableFromDGV(dataGridView1);
DataSet dS = new DataSet();
dS.Tables.Add(dT);
dS.WriteXml(File.OpenWrite(savefile.FileName));
}
}
}
Finaly i use save textboxes and datagridview through dataset.WriteXml
//XML save throught dataset
private void XMLsave(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = false;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "OrderData";
dt.Columns.Add("OrderNr");
dt.Columns.Add("Custommer");
dt.Columns.Add("Material");
dt.Columns.Add("MaterialCode");
ds.Tables.Add(dt);
DataTable dt1 = new DataTable();
dt1.TableName = "Data";
dt1.Columns.Add("Lenght");
dt1.Columns.Add("Width");
dt1.Columns.Add("Qty");
ds.Tables.Add(dt1);
DataRow row = ds.Tables["OrderData"].NewRow();
row["OrderNr"] = tbOrderNr.Text;
row["Custommer"] = tbCustommer.Text;
row["Material"] = tbMaterial.Text;
row["MaterialCode"] = tbForm2MatCode.Text;
ds.Tables["Data"].Rows.Add(row);
foreach (DataGridViewRow r in dataGridView1.Rows)
{
DataRow row1 = ds.Tables["Data"].NewRow();
row1["Lenght"] = r.Cells[0].Value;
row1["Width"] = r.Cells[1].Value;
row1["Qty"] = r.Cells[2].Value;
ds.Tables["Data"].Rows.Add(row1);
}
ds.WriteXml("test.xml");
dataGridView1.AllowUserToAddRows = true;
}
and then load it with:
private void XmlLoad(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml("test.xml");
tbOrderNr.Text = ds.Tables["OrderData"].Rows[0][0].ToString();
tbCustommer.Text = ds.Tables["OrderData"].Rows[0][1].ToString();
tbMaterial.Text = ds.Tables["OrderData"].Rows[0][2].ToString();
tbForm2MatCode.Text = ds.Tables["OrderData"].Rows[0][3].ToString();
foreach (DataRow item in ds.Tables["Data"].Rows)
{
dataGridView1.AllowUserToAddRows = false;
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = tem["Lenght"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["Width"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["Qty"].ToString();
dataGridView1.AllowUserToAddRows = true;
}
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 = "";
}
I want to fill grid view with textbox and dropddown list values recursively on button click.Currently it is binding only once.I am new to ASP.NET.Help would be highly appreciated
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
for (int intCnt = 0; intCnt < grd.Rows.Count - 1; intCnt++)
{
if (grd.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Resource"] = grd.Rows[intCnt].Cells[0];
dr["available"] = grd.Rows[intCnt].Cells[1];
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Please try this hope it will help
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
foreach(GridViewRow row in grd.Rows)
{
dr = dt.NewRow();
dr["Resource"] = row.Cells[0].Text;
dr["available"] =row.Cells[1].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Use following code:
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = defineColumn();
DataRow dr;
foreach (GridViewRow grow in grdChMedicine.Rows)
{
dr = dt.NewRow();
dr["Diagnosis"] = grow.Cells[1].Text;
dr["DiagnosisId"] = grow.Cells[2].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Diagnosis"] = ddldiagnosis.SelectedItem.ToString();
dr["DiagnosisId"] = ddldiagnosis.SelectedValue;
dt.Rows.Add(dr);
ViewState["ChMedicine"] = dt;
grdChMedicine.DataSource = dt;
grdChMedicine.DataBind();
}
private DataTable defineColumn()
{
DataTable dt = new DataTable();
dc = new DataColumn("Diagnosis");
dt.Columns.Add(dc);
dc = new DataColumn("DiagnosisId");
dt.Columns.Add(dc);
return dt;
}
I am developing an online exam system project using ASP.NET (C#) & SQL Sever.
This is my code. I have a problem in implementing code for next & previous button. Please suggest me the answer. Thank you.
public partial class Default : Page
{
int count;
string ans;
int[] a=new int[5];
int t;
int ctr;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DateTime myDate;
DataTable dt = new DataTable();
DataRow dr;
public void Show()
{
Session["Answered"] = dt;
View v = this.View1;
Label l = default(Label);
l = (Label)v.FindControl("Label1");
l.Text = dt.Rows[ctr]["Serial"] + ".";
l = (Label)v.FindControl("Label2");
l.Text = dt.Rows[ctr]["question"].ToString();
RadioButtonList r = default(RadioButtonList);
r = (RadioButtonList)v.FindControl("RadioButtonList1");
r.Items.Clear();
r.Items.Add(dt.Rows[ctr]["choice1"].ToString());
r.Items.Add(dt.Rows[ctr]["choice2"].ToString());
r.Items.Add(dt.Rows[ctr]["choice3"].ToString());
r.Items.Add(dt.Rows[ctr]["choice4"].ToString());
r.SelectedIndex = Convert.ToInt32(dt.Rows[ctr]["selected"]);
Session["ctr"] = ctr;
}
protected void Timer1_Tick(object sender, System.EventArgs e)
{
DateTime mydate2 = DateTime.Now;
DateTime mydate3 = default(DateTime);
try
{
mydate3 = Convert.ToDateTime((myDate - mydate2).ToString());
this.Label5.Text = "Time Left: " + mydate3.ToShortTimeString();
}
catch (Exception ex)
{
this.Label5.Text = "Error Setting up the Timer. Contact Admin";
}
if (mydate3.ToShortTimeString() == "00:00:00")
{
int marks = 0;
Session["Answered"] = dt;
Response.Redirect("default3.aspx?marks=" + marks);
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
DateTime myDate = new DateTime();
myDate =Convert.ToDateTime(Request.Cookies["start"].Value);
if (!IsPostBack) {
this.MultiView1.ActiveViewIndex = 0;
conn.Open();
cmd.Connection = conn;
Random arbit = new Random();
for (int i = 0; i <= a.GetUpperBound(0); i++) {
t = arbit.Next(1, 10);
if (Array.IndexOf(a, t) == -1) {
a[i] = t;
} else {
goto X;
}
}
for (int i = 0; i <= 4; i++)
{
cmd.CommandText = "select * from test where Serial=" + a[i];
da.SelectCommand = cmd;
da.Fill(ds, "test");
}
conn.Close();
dt = new DataTable("Answered");
dt.Columns.Add("Serial", typeof(int));
dt.Columns.Add("question", typeof(string));
dt.Columns.Add("choice1", typeof(string));
dt.Columns.Add("choice2", typeof(string));
dt.Columns.Add("choice3", typeof(string));
dt.Columns.Add("choice4", typeof(string));
dt.Columns.Add("correct", typeof(string));
dt.Columns.Add("selected", typeof(int));
DataRow r = null;
foreach (DataRow r_loopVariable in ds.Tables["test"].Rows) {
r = r_loopVariable;
dr = dt.NewRow();
dr["Serial"] = dt.Rows.Count + 1;
dr["question"] = r["question"];
dr["choice1"] = r["choice1"];
dr["choice2"] = r["choice2"];
dr["choice3"] = r["choice3"];
dr["choice4"] = r["choice4"];
dr["correct"] = r["correct"];
dr["selected"] = -1;
dt.Rows.Add(dr);
}
Session["Answered"] = dt;
Show();
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
Session["ctr"] = ctr;
Session["Answered"] = dt;
Session["ctr"] = ctr;
ctr += 1;
Show();
if (ctr == 4)
{
this.btnNext.Enabled = false;
}
this.btnPrev.Enabled = true;
}
protected void btnPrev_Click(object sender, EventArgs e)
{
Session["ctr"] = ctr;
Session["Answered"] = dt;
ctr = ctr - 1;
if (ctr == 0)
{
this.btnPrev.Enabled = false;
}
Session["ctr"] = ctr;
this.btnNext.Enabled = true;
Show();
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
Session["Answered"] = dt;
}
protected void btnShowMarks_Click(object sender, EventArgs e)
{
int marks = 0;
Session["Answered"] = dt;
Response.Redirect("default3.aspx?marks=" + marks);
Session["marks"] = dt;
int []b=new int[6];
foreach (int c in b)
{
RadioButtonList1.SelectedIndex.ToString();
}
}
}
I would suggest you to use the Wizard control.
Here are some examples:
http://msdn.microsoft.com/en-us/magazine/cc163894.aspx
http://www.codeproject.com/KB/aspnet/Wizard_Control.aspx
Since you seem to develop a wizard-like form did you consider using the Wizard control.
You can Fetch random data from DB and store it in a dataset. Then there you can get questions in usual manner. Then you can fetch questions using a variable which will store the question number to get previous and next questions. If user clicks on Previous then variable - 1 also +1 if next