Dynamically creating session on Button Click - c#

Actually i have created one session object and i am storing multiple textbox, radio & checkbox value in that session.
Here is my Code(My Insertion page, where i'll insert values and store in session).
protected void btnRegister_Click(object sender, EventArgs e)
{
//Creating DataTable dt
DataTable dt = new DataTable();
//Creating DataTable Columns
dt.Columns.Add("FName", typeof(string));
dt.Columns.Add("MName", typeof(string));
dt.Columns.Add("LName", typeof(string));
dt.Columns.Add("Phone", typeof(string));
dt.Columns.Add("EId", typeof(string));
dt.Columns.Add("State", typeof(string));
dt.Columns.Add("City", typeof(string));
dt.Columns.Add("Country", typeof(string));
dt.Columns.Add("PCode", typeof(string));
dt.Columns.Add("Gender", typeof(string));
dt.Columns.Add("AOI", typeof(string));
dt.Rows.Add(txtFN.Text, txtMN.Text, txtLN.Text, txtPhone.Text, txtEId.Text, ddlState.Text, ddlCity.Text, txtCountry.Text, txtPCode.Text, rdGender.SelectedValue, cbAOI.SelectedValue);
//Creating Session object to store DataTable dt
Session.Add("Insert", dt);
lblMandatory.Text = "Successfully Inserted into Database";
System.Threading.Thread.Sleep(1000);
Response.Redirect("Home.aspx");
}
I just wanted to know, is there any way to create new session whenever i click Register button i.e., i don't want to overwrite existing session, but on each button click, i want to create new session automatically.
My Home Page, where i'll display this dataTable using GridView
protected void Page_Load(object sender, EventArgs e)
{
if ((!IsPostBack) && (Session["Insert"] != null))
{
//At another place you retrieve datatable:
DataTable dt = new DataTable();
dt = (DataTable)Session["Insert"];
//Binding GridView with DataTable dt
gdvView.DataSource = dt;
gdvView.DataBind();
}
}
My Problem is, everytime GridView column get replaced with new GridView column, since my session get replaced with new values.
So is there any way, i can store new session value into gridview without loosing previous values from gridview.

Ok I get what's your problem now.
You don't need to create a new session everytime
here is a snippets;
DataTable dt;
if (Session["Insert"]_== null) //or nothing
{
dt = new DataTable();
}
else
{
dt = (DataTable)Session["Insert"];
}
//Add to dt.Rows here
//Save it again to Session["Insert"]
//Then bind dt to GridView again
This way you won't need new sessions and your dt data is retained,

//Creating DataTable dt
DataTable dt = new DataTable(); //Declare dt only once. If this wont work put it in a get set property.
protected void Page_Load(object sender, EventArgs e)
{
if ((!IsPostBack)
{
CreateDataTable();
LoadDataTable();
}
gdvView = Nothing; //or Null;
gdvView.DataSource = dt;
gdvView.DataBind();
}
protected void CreateDataTable()
{
//Creating DataTable Columns
dt.Columns.Add("FName", typeof(string));
dt.Columns.Add("MName", typeof(string));
dt.Columns.Add("LName", typeof(string));
dt.Columns.Add("Phone", typeof(string));
dt.Columns.Add("EId", typeof(string));
dt.Columns.Add("State", typeof(string));
dt.Columns.Add("City", typeof(string));
dt.Columns.Add("Country", typeof(string));
dt.Columns.Add("PCode", typeof(string));
dt.Columns.Add("Gender", typeof(string));
dt.Columns.Add("AOI", typeof(string));
}
protected void LoadDataTable()
{
if ((Session["Insert"] == null) //or (Session["Insert"] == nothing)
{
Session.Add("Insert", dt);
}
else {
dt = (DataTable)Session["Insert"];
{
}
protected void btnRegister_Click(object sender, EventArgs e)
{
//Do whatever you need to do as is
dt.Rows.Add(txtFN.Text, txtMN.Text, txtLN.Text, txtPhone.Text, txtEId.Text, ddlState.Text, ddlCity.Text, txtCountry.Text, txtPCode.Text, rdGender.SelectedValue, cbAOI.SelectedValue);
LoadDataTable();
/* Remove this block if you don't need it here */
gdvView = Nothing; //or Null;
gdvView.DataSource = dt;
gdvView.DataBind();
/* Remove this block if you don't need it here */
lblMandatory.Text = "Successfully Inserted into Database";
System.Threading.Thread.Sleep(1000);
Response.Redirect("Home.aspx");
}

You can try the following code. Here, I am testing if there already exist a value in this session, "Insert". If yes, a new row is being appended to it otherwise, a new DataTable is created.
protected void btnRegister_Click(object sender, EventArgs e)
{
//Creating DataTable dt
DataTable dt;
if (Session["Insert"] == null) //or nothing
{
dt = new DataTable();
//Creating DataTable Columns
dt.Columns.Add("FName", typeof(string));
dt.Columns.Add("MName", typeof(string));
dt.Columns.Add("LName", typeof(string));
dt.Columns.Add("Phone", typeof(string));
dt.Columns.Add("EId", typeof(string));
dt.Columns.Add("State", typeof(string));
dt.Columns.Add("City", typeof(string));
dt.Columns.Add("Country", typeof(string));
dt.Columns.Add("PCode", typeof(string));
dt.Columns.Add("Gender", typeof(string));
dt.Columns.Add("AOI", typeof(string));
}
else
{
dt = Session["Insert"] as DataTable;
}
dt.Rows.Add(txtFN.Text, txtMN.Text, txtLN.Text, txtPhone.Text, txtEId.Text, ddlState.Text, ddlCity.Text, txtCountry.Text, txtPCode.Text, rdGender.SelectedValue, cbAOI.SelectedValue);
//Creating Session object to store DataTable dt
Session["Insert"] = dt;
lblMandatory.Text = "Successfully Inserted into Database";
System.Threading.Thread.Sleep(1000);
Response.Redirect("Home.aspx");
}

Related

Displaying information in same form c#

The following code is used by me to pass the data from 3 text boxes(in form 2) to a data grid view (in form 1). The data is passed successfully but the only problem I face is that data is passed to a new form of type f1!
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
DataTable dt1 = new DataTable();
f1.dataGridView2.DataSource = dt1;
dt1.Columns.Add("MessageID", typeof(string));
dt1.Columns.Add("Name", typeof(string));
dt1.Columns.Add("Number", typeof(string));
DataRow dr = dt1.NewRow();
dr["MessageID"] = IDtext.Text; ;
dr["Name"] = nameText.Text;
dr["Number"] = numberText.Text;
dt1.Rows.Add(dr);
f1.Show();
}
So each time I pass information a new window is created and the previous data i sent does not appear in the data grid view!How can i correct this?
Your refactored code:
class Form2
{
delegate void PassDataDelegate(DataTable dt1);
public event PassDataDelegate PassData;
private void button1_Click(object sender, EventArgs e)
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("MessageID", typeof(string));
dt1.Columns.Add("Name", typeof(string));
dt1.Columns.Add("Number", typeof(string));
DataRow dr = dt1.NewRow();
dr["MessageID"] = IDtext.Text; ;
dr["Name"] = nameText.Text;
dr["Number"] = numberText.Text;
dt1.Rows.Add(dr);
// This is where you call your event
PassData(dt1);
}
}
class Form1
{
// Your existing Form1 class definition
private static void YourMethodWhereYouLaunchForm2()
{
Form2 f2 = new Form2();
// Add this handler and you will get it invoked whenever you ask from Form2
f2.PassData += Handle_DataPassed;
}
private void Handle_DataPassed(DataTable dt1)
{
// This is where you post the data now to the grid.
dataGridView2.DataSource = dt1;
}
}

Windows Form DataGridView not getting DataSet

What is wrong with my code?
dataSet = new DataSet();
dataTable = dataSet.Tables.Add("Items");
dataTable.Columns.Add("Site", typeof(string));
dataTable.Columns.Add("ItemID", typeof(UInt64));
dataTable.Columns.Add("ItemName", typeof(string));
dataTable.Columns.Add("ListedPrice", typeof(decimal));
dataTable.Columns.Add("Currency", typeof(string));
dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["ItemID"] };
string site = "mysite";
UInt64 itemId = 44322;
string itemName = "werwer";
decimal listedPrice = 345345;
string currency = "USD";
dataTable.Rows.Add(site, itemId ,itemName, listedPrice, currency);
dataGridView1.DataSource = dataSet.Tables["Items"];
When I run it, it does not enter the row to the GridView, simply adding a blank line
EDIT
I found the problem, it was because I manually created the cells in VS IDE.
How can I still work with the IDE because I want to fix the layout not by code
Try this once..
DataSet dataSet = new DataSet();
DataTable dataTable = dataSet.Tables.Add("Items");
dataTable.Columns.Add("Site", typeof(string));
dataTable.Columns.Add("ItemID", typeof(UInt64));
dataTable.Columns.Add("ItemName", typeof(string));
dataTable.Columns.Add("ListedPrice", typeof(decimal));
dataTable.Columns.Add("Currency", typeof(string));
dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["ItemID"]
dataTable.Rows.Add("mysite",44322,"werwer", 345345,"USD");
dataGridView1.DataSource = dataSet.Tables["Items"]

How to add a row into datatable on button click event?

In Windows Forms, I want to add row by row into DataGridView on button click event by taking the values from other controls. I am using DataTable in this case and it is bound to DataGridView.
I am using the following code and it is working fine when the data is inserted for the first time. But my problem is when I click the button for the second time, the first row is overwritten with the second row of data.
private void btnAddToGrid_Click(object sender, EventArgs e)
{
LoadDataGridView();
}
private void LoadDataGridView()
{
dgvAdjustment.DataSource = GetAdjustmentTable();
}
private DataTable GetAdjustmentTable()
{
DataTable adjustmentTable = new DataTable();
DataColumn dataColumn;
dataColumn = new DataColumn("SourceOutletID", typeof(int));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("DestinationOutletID", typeof(int));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("TransactionDate", typeof(DateTime));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("MaterialName", typeof(string));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("AdjustmentType", typeof(int));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("CurrentBalance", typeof(decimal));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("AdjustmentQty", typeof(decimal));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("NewBalance", typeof(decimal));
adjustmentTable.Columns.Add(dataColumn);
DataRow dataRow = adjustmentTable.NewRow();
dataRow[0] = cmbSourceOutlet.SelectedValue;
dataRow[1] = cmbDestinationOutlet.SelectedValue;
dataRow[2] = TransDateTimePicker.Value;
dataRow[3] = cmbMaterialName.SelectedValue;
dataRow[4] = cmbAdjustmentType.SelectedValue;
dataRow[5] = Convert.ToDecimal(lblCurBalVal.Text);
dataRow[6] = Convert.ToDecimal(lblAdjVal.Text);
dataRow[7] = Convert.ToDecimal(lblNewQtyVal.Text);
int insertPosition = adjustmentTable.Rows.Count;
adjustmentTable.Rows.InsertAt(dataRow, insertPosition);
return adjustmentTable;
}
In ASP .NET applications, I use the session state to check whether DataTable is null by using the following code:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//Check if previous session is exist
if (Session["MyTable"] == null)
{
dtMyTable = new DataTable("MyTable");
dtMyTable.Columns.Add("Id", typeof(int));
dtMyTable.Columns.Add("LName", typeof(string));
}
else
{
//If yes then get it from current session
dtMyTable = (DataTable)Session["MyTable"];
}
//Add new row every time
DataRow dt_row;
dt_row = dtMyTable.NewRow();
dt_row["Id"] = TextBox1.Text;
dt_row["LName"] = TextBox2.Text;
dtMyTable.Rows.Add(dt_row);
//Update session table
Session["MyTable"] = dtMyTable;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
What can I do and how can I make the changes to get the right solution in Windows Forms? Any help will be much appreciated!
In GetAdjustmentTable, you are recreating adjustmentTable every time. So a new row will just overwrite the existing one.
You need to modify the code such that adjustmentTable is only created just once and subsequent calls add rows to it. One way to do that would be to make it a private field and to check if it's null, and create it if it is:
private DataTable _adjustmentTable;
private DataTable GetAdjustmentTable()
{
if (adjustmentTable == null)
{
adjustmentTable = new DataTable();
}
....

Can't bind DataTable to GridView

Hey guys I've just started programming and I'm running into a problem. The new Datatable i created doesnt show in GridView2 when button1 is clicked. Although it is filled with data from the "planning" table(checked that dtPlanning is filled with the TextBoxes in comment).
So in short: I want to get DataTable planning into the new DataTable dtPlanning and display it in a gridview.
Code Behind:
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dtPlanning = new DataTable();
dtPlanning.Columns.Add("Courseday", typeof(int));
dtPlanning.Columns.Add("Part", typeof(string));
dtPlanning.Columns.Add("Design", typeof(string));
dtPlanning.Columns.Add("Lesson", typeof(string));
//DataRow dr = planning.Rows[1];
//TextBox2.Text = (dr["Daynumber"]).ToString();
//TextBox3.Text = (dr["Part"]).ToString();
//TextBox4.Text = (dr["Design"]).ToString();
//TextBox5.Text = (dr["Lesson"]).ToString();
for (int i = 0; i < dtPlanning.Rows.Count; i++)
{
DataRow dr = dtPlanning.NewRow();
foreach (DataRow datarow in planning.Rows)
{
dtPlanning.Rows.Add(datarow);
}
}
GridView2.DataSource = dtPlanning;
GridView2.DataBind();
}
Source code:
<asp:GridView ID="GridView2" runat="server">
Thank you for your help.
Logically, dtPlanning.Rows.Count = 0 because this table is just initialized!
Secondly, you cannot Add a row from one table to another, user Import
for (int i = 0; i < planning.Rows.Count; i++)
{
dtPlanning.ImportRow(planning.Rows[i]);
}
I wonder why don't you just use the table planning?
You must:
Add to DataSet a new DataTable
Add to DataTable a new Columns
And GridView2.DataSource=YourNameDataSet.Tables[index_of_DataTable_in_DataSet].DefaultView;

Filling DataTable from GridView in C#

How can I fill DataTable from GridView in ASP.NET?
Simply, you can do like this:
BindingSource bindingSource = (BindingSource )yourGridView.DataSource;
DataTable yourDataTable= (DataTable ) bindingSource .DataSource;
Another way, you can do like this:
DataTable yourDataTable = yourGridView.DataSource as DataTable
I solved like this
if (myGridView.Rows.Count > 0)
{
var dt = new DataTable();
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(Int64));
dt.Columns.Add("Column3", typeof(string));
foreach (GridViewRow row in gd_endYearSchool.Rows)
{
var id = row.Cells[1].Text;
//for find textbox
var tb1 = row.Cells[2].FindControl("tbNr") as TextBox;
int nrord = 0;
if (tb1 != null)
{
var ord = tb1.Text;
if (!Int64.TryParse(ord, out nrord))
{
nrord = 0;
}
}
var text=row.Cell[3].text;
dt.Rows.Add(id,nrord,text);
}
}
you can fill datatable from gridview with foreach
I'll do like this, i think this'll help u.
public void Data_table()
{
Session["Data"] = "";
DataTable dt = new DataTable();
//Add Columns to the datatable
dt.Columns.Add("c1");
dt.Columns.Add("c2");
dt.Columns.Add("c3");
//Define a datarow for the datatable dt
DataRow dr = dt.NewRow();
//Now add the datarow to the datatable
Session["Data"] = dt;
RadGrid1.DataSource = dt;
RadGrid1.Rebind();
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
if (((System.Data.DataTable)(Session["Data"])).Rows.Count.ToString() != "")
{
RadGrid1.DataSource = Session["Data"];
}
}
Thank you..,

Categories