I have an asp.net form with a textbox and a button. Each time the button is clicked I need the text from the textbox to be added as a new row in a table, which will then be presented on a gridview.
I have managed to add the text from the textbox as a new row, but every time I click the button it seems the table is not saved (meaning - I end up with only one row).
public partial class buildTable : System.Web.UI.Page
{
DataTable dt = new DataTable();
public int namesCounter;
protected void Page_Load(object sender, EventArgs e)
{
dt.Columns.Add("ID", typeof(Int16));
dt.Columns.Add("name", typeof(string));
namesCounter = 0;
names_GV.DataSource = dt;
}
protected void addName_Click(object sender, EventArgs e)
{
namesCounter += 1;
DataRow dtrow = dt.NewRow();
dtrow["ID"] = namesCounter;
dtrow["name"] = newName_TXT.Text;
dt.Rows.Add(dtrow);
names_GV.DataBind();
}
}
I'm guessing this has something to do with postback...
The problem here lies in the "statelessness" of asp.net. In short, each round trip to the page (first visit, post-backs) creates a new instance of buildTable, thus re-instantiating your dt variable and setting it as data source to your grid.
Consider sending the user input to some sort of persistence layer that enables you to hold the data per-user and rebinding said data with each post back. The strategy which could be used here really depends on the size and context of your application.
Please refer to:
Microsoft's ASP.NET State Management Overview (http://msdn.microsoft.com/en-us/library/75x4ha6s(v=vs.100).aspx) for state management strategies
Microsoft's State Management Recommendations (http://msdn.microsoft.com/en-us/library/z1hkazw7(v=vs.100).aspx) for state management recommendations
Introduction to ASP.NET Web Pages (http://msdn.microsoft.com/en-us/library/ms178125(v=vs.100).aspx) for further details about the page lifetime
You need to Add the ID and Table to Viewstate so that the State is retained because, here we are not saving the Data in the Database. So every time the Page Loads, the Data is Null unless we save it in a viewstate.
Check with the Code below:-
It will run perfectly :-
DataTable dt = new DataTable();
public int namesCounter;
protected void Page_Load(object sender, EventArgs e)
{
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("name", typeof(string));
//namesCounter = 0;
if (!IsPostBack)
{
ViewState["Number"] = 0;
ViewState["table"] = dt;
}
names_GV.DataSource = dt;
names_GV.DataBind();
}
protected void addName_Click(object sender, EventArgs e)
{
dt = (DataTable)ViewState["table"];
namesCounter = Convert.ToInt32(ViewState["Number"]) + 1;
ViewState["Number"] = namesCounter;
DataRow dtrow = dt.NewRow();
dtrow[0] = namesCounter;
// dtrow["ID"] = namesCounter;
dtrow["name"] = newName_TXT.Text;
dt.Rows.Add(dtrow);
ViewState["table"] = dt;
names_GV.DataSource = dt;
names_GV.DataBind();
}
This code is working properly with me,
add them in button click event
:
DataTable dt_items = new DataTable();
dt_items.Columns.Add("Item");
dt_items.Columns.Add("Quantity");
if (grid_items.Rows.Count > 0)
{
foreach (GridViewRow row in grid_items.Rows)
{
dt_items.Rows.Add(row.Cells[0].Text,row.Cells[1].Text);
}
}
dt_items.Rows.Add(ddl_item.SelectedItem.Text, txt_itemAmount.Text);
grid_items.DataSource = dt_items;
grid_items.DataBind();
Related
When I click the submit button,I cannot see the data in the gridview.What changes do I need to make in order to see the data in the GridView?
protected void Button1_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ProductId");
table.Columns.Add("ProductName");
table.Columns.Add("ExpiryDate");
table.Columns.Add("Price");
table.Columns.Add("LotNumber");
DataRow dr = table.NewRow();
dr["ProductId"] = ProductId.Text;
dr["ProductName"] = ProductName.Text;
dr["ExpiryDate"] = ExpiryDate.Text;
dr["Price"] = Price.Text;
dr["LotNumber"] = LotNumber.Text;
table.Rows.Add(dr);
GridView2.DataSource = table;
GridView2.DataBind();
}
According the code, you have two GridView. Verify you update the right one.
I have created a data table of four columns in my global.asax file. I am adding rows only to two columns of the data table in the global.asax file. I am trying to add the other two rows from a different .aspx.cs file which is under the same project. When I try to add the row, it gives me an error
"the name "dr" does not exists in the current context".
My code:
login.aspx.cs:
protected void btnLogin_Click(object sender, EventArgs e)
{
if(txtPassword.Text == "")
{
Server.Transfer("Main.aspx", true);
}
if(txtUserName.Text!= "" && txtPassword.Text!= "")
{
Server.Transfer("Userlog.aspx", true);
}
dr["username"] = Session["UserName"]; // username
dr["login_time"] = Session["LoginTime"]; //login time
}
global.asax:
void Session_Start(Object s, EventArgs e)
{
Application.Lock();
dt = new DataTable();
dt.Columns.Add(new DataColumn("session_id", System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("username", System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("login_time", System.Type.GetType("System.DateTime")));
dt.Columns.Add(new DataColumn("ip_address", System.Type.GetType("System.String")));
Application["visitorTable"] = dt;
DataRow dr = dt.NewRow();
dr["session_id"] = (System.String)Session.SessionID; // session id
dr["ip_address"] = Request.ServerVariables["SERVER_NAME"]; //ip-address
dt.Rows.Add(dr);
//dt = (DataTable)Application["visitorTable"];
Application["visitorTable"] = dt;
DataView view = new DataView(dt);
Application.UnLock();
}
It will through since dr variable doesnt exists. If you want the datatable row in session object then store the datatable row with some key word and then retrieve it.
Session["RowDataTable"] = dr;
Then login page
var dr = Session["RowDataTable"] as DataRow;
Hmm don't realy know where to start:
Firstly your defined variables dt and dr are only available in the scope of the method Session_Start(){}.
That means, after the method-call, the both variables are not available anymore.
Secondary, if you need to access your Data also outside of that method, you should store it in an private variable:
private DataTable _myDataTable;
or in a public Propertiy to access it from outside the current class:
public DataTable MyDataTable { get; set }
You should also inform you about the static modifier:
https://msdn.microsoft.com/de-de/library/98f28cdx.aspx
Hope that helps you a little bit.
And for that what you want in the current situation, the answer of Mahesh Malpani maybe leads you to.
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();
}
....
I am using C# asp.net, I have a class that return an ArrayList from the database. When the user presses a button on the page. So, is there is a way to fill it? Right now I am trying to find a datagridview.
Here is an example
Source : http://www.etechpulse.com/2012/10/bind-array-list-elements-to-grid-view.html
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// Single Dimensional array
private void BindGridview()
{
string[] arrlist = // your function that gets the arraylist
DataTable dt = new DataTable();
// you need to do the following for each column
dt.Columns.Add("Name");
for (int i = 0; i < arrlist.Count(); i++)
{
dt.Rows.Add();
dt.Rows[i]["Name"] = arrlist[i].ToString();
}
gvarray.DataSource = dt; //gvarray is your GridView defined in aspx design
gvarray.DataBind();
}
Also do not forget to add AutoGenerateColumns="false" if you want to fill the grid programmatically.
I have used the following code to display data from a TextBox to a GridView without saving the data to the database(Two TextBoxes and a Button). When I enter the Name and City in the TextBoxes, and click on the Button, those values will be displayed in the Gridview. It is working as expected without any errors. But I want to tweak the code a bit so that the GridView should be able to add new data from the Textbox by retaining the old data as it is in the Gridview (multiple rows should be displayed in the Gridview instead of single rows).
It is a web-based ASP.NET application using C# coding (Visual Studio 2010).
Can you make the necessary changes to the code given below so as to implement the above functionality?
public partial class _Default : System.Web.UI.Page
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
}
You have to persists your data between postbacks, you have many options here: by Session, ViewState, Cache and some other.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostback)
{
dt = Session["data_table"] as DataTable;
}
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
if (dt == null)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
}
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
Session["data_table"] = dt;
}