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.
Related
Looking for a way to dynamically delete rows from a datalist, providing a user a way to 'clean up' their input interface. The asp datalist gets loaded from SQL, then the user gets to manipulate the table before sending it on to another database.
I have a functioning 'addRows' by using a datatable session variable, adding rows to it then re-binding to the datalist, however I can't seem to get the same function with deleting rows.
Current logic is to use datalist 'delRows' command, get current typed-in or modified data from the asp datalist, assign it to a datatable, loop thru datatable and delete rows where certain fields are empty, then re-bind datatable to asp datalist.
Current code workup, but cannot get dt filled, error "dt = null" :
if (e.CommandName == "delRows")
{
DataList DataList1 = (DataList)FindControl("DataList1"); //find datalist in current state
Session["dataList1"] = DataList1; //assign datalist to session variable
DataTable dt = Session["dataList1"] as DataTable; //populate datatable with datalist session
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
string check = dr["item_no"].ToString();
if (check == String.Empty)
{
dr.Delete();
}
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
Hopefully there is a better way to accomplish this! Not to mention working....
For any future info seekers: Had to loop thru table to get most current textbox text into dt, then modify dt datatable in code behind, then rebind dt to datalist.
protected void doDataTable(string command, int e)
{
DataTable dt = new DataTable();
dt.Columns.Add("no", typeof(string));
dt.Columns.Add("desc", typeof(string));
dt.Columns.Add("code", typeof(string));
dt.Columns.Add("measure", typeof(string));
dt.Columns.Add("qty", typeof(int));
dt.Columns.Add("price", typeof(double));
foreach (DataListItem item in DataList4.Items)
{
string no = ((TextBox)item.FindControl("no")).Text;
string desc = ((TextBox)item.FindControl("desc")).Text;
string code = ((TextBox)item.FindControl("code")).Text;
string measure = ((TextBox)item.FindControl("measure")).Text;
int qty = Convert.ToInt16(((TextBox)item.FindControl("qty")).Text);
double price = Convert.ToDouble(((TextBox)item.FindControl("price")).Text.TrimStart('$'));
dt.Rows.Add(no, desc, code, measure, qty, price);
}
if (command == "add")
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
DataList4.DataSource = dt;
DataList4.DataBind();
}
else if (command == "del")
{
dt.Rows[e].Delete();
DataList4.DataSource = dt;
DataList4.DataBind();
}
}
Called with:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "addRow")
{
doDataTable("add", e.Item.ItemIndex);
}
if (e.CommandName == "delRows")
{
doDataTable("del", e.Item.ItemIndex);
}
}
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 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();
I have created two TextBoxes to enter the FirstName and LastName of an employee and a button in a web-based ASP.NET application using C# on Visual studio 2010.when I click on the button , the values that I enter in the TextBoxes should be displayed in a Gridview without being stored in the database.
How can I do that? Can you provide a sample code to execute the above mentioned functionality?
This is a working code..
protected void Page_Load(object sender, EventArgs e)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("FIRST NAME");
DataColumn dc2 = new DataColumn("LAST NAME");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
DataRow dr1 = dt.NewRow();
GridView1.DataSource = dt;
GridView1.DataBind();
}
DataTable dt;
protected void Button1_Click(object sender, EventArgs e)
{
DataRow dr1 = dt.NewRow();
dr1[0] = TextBox1.Text;
dr1[1] = TextBox2.Text;
dt.Rows.Add(dr1);
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can access gridview in code like that:
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
After you can access in that gridview will be methods to renew/add/delete information in client side. But notice, that you also have to tell your server-side that you renewed the information in DB, so he can save changes to DB.
I expect that you should send ajax request for renewing data in DB, and use the code to access grid from javascript and renew data in client-side over javascript.
Take the values which you have entered in textbox in a DataTable and the give that dataTable as a datasource to that datagrid.
Check this link
http://forums.asp.net/t/1672122.aspx/1
the code you provided works fine. but it will add only one record to GridView. If you added a new record then the old data will be replaced. So we have to preserve the old record.
Just enter the below code to the button click event.
protected void Button1_Click(object sender, EventArgs e)
{
if(Session["Data"] == null) //Checking if the session contain any value.
{
DataTable dt = new DataTable(); //creating the columns.
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("Stock");
DataRow dr = dt.NewRow(); //Create a new row and add the row values.
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt; //Populate values to Gridview.
GridView1.DataBind();
Session["Data"] = dt; //Storing that table into session.
}
else
{
DataTable dt = new DataTable();
dt = (DataTable)Session["Data"]; //Retrieve the stored table from session.
DataRow dr = dt.NewRow(); //Adding a new row to existing table.
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dr[2] = TextBox3.Text;
dt.Rows.Add(dr);
GridView1.DataSource = dt; //Populate new table values to Gridview.
GridView1.DataBind();
Session.Remove("Data"); //Clear the session.
Session["Data"] = dt; //Store the new table to the session.
}
}
private int id = 0;
private void dataGridView1_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int RowIndex = e.RowIndex;
id= Convert.ToInt32(dataGridView1.Rows[RowIndex].Cells[0].Value.ToString());
textBox1.Text = dataGridView1.Rows[RowIndex].Cells[1].Value.ToString();
textBox2.Text = dataGridView1.Rows[RowIndex].Cells[2].Value.ToString(); textBox3.Text = dataGridView1.Rows[RowIndex].Cells[3].Value.ToString();
textBox4.Text = dataGridView1.Rows[RowIndex].Cells[4].Value.ToString();
}
My homework is in ASP.NET and my prof wants me to delete a row from a gridview that doesn't use a SqlDataSource. Is this possible? Because I think my prof wants to fail me just because I asked a question and he wasn't able to answer it.
Yes you can delete a row from gridview that doesn't use sqldatasource. All you have to do is delete the row from the source (whatever the source is...), that is bind to your gridview.
heres sample code for the issue:
public static DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
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)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = "column1cell";
dr["Column2"] = "column2cell";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
if (dt.Rows.Count > 0)
{
dt.Rows.RemoveAt(0);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
not the best code, but if your prof wants you to do, here you are.
hope this helps you...
I you Just want to delete the row find the row index and the simply call the method
datagridview.rows.removeat(rowindex);
There is a better way without having to rebind the Gridview and it forcing a call to the SqlDataSource.
Use ViewState.
When you load the Gridview, save the "data" into a ViewState variable.
ie:
//ok let's load the gridview with data as normal and display it
//'sdsClasses' is the SQL data source
gvStudents.DataSourceID = "sdsClasses";
gvStudents.DataSource = null; // Null out the source, as we have a SourceID instead
gvStudents.DataBind(); //load the gridview and display it
//save the data in a viewstate for later use
DataView dvClasses = (DataView)sdsClasses.Select(DataSourceSelectArguments.Empty);
DataTable dt = new DataTable();
if (dv != null)
{
dt = dvClasses.ToTable();
ViewState["gv"] = dt;
}
So now when ever the Gridview loads, you have the data its used in memory as a ViewState.
If you need to delete a row, do this ...
In my example I am using a search feature to look for the row I want to delete, based on a SelectValue from a dropdownlist control. You'll have to use something like that to pin-point the row you want to delete. If you wanted to delete the last row, then do a ForEach on the DataTable, row-by-row until you get to the last row and delete!
//Load the dataview that was already saved in the ViewState
DataTable dt = (DataTable)ViewState["gv"];
//find the student in the datatable, row by row
bool found = false;
bool wsAtt = false; //flag to indicate if the student is already in the roll or not saved yet (ie: sdsClasses recordset)
foreach (DataRow dr in dt.Rows)
{
//compare studentID in the datatable with the selected value of the student to delete
//check that the field has TECNQ studentIDs otherwise use the 2nd cell in the row
if (dr[0].ToString().Contains("NQ"))
found = (found || dr[0].ToString() == ddlRemoveStudents.SelectedValue);
else
{
found = (found || dr[1].ToString() == ddlRemoveStudents.SelectedValue);
wsAtt = true;
}
//he should!
if (found)
{
//remove the row to the datatable
dt.Rows.Remove(dr);
//Bind the grid view to the datatable and refresh
gvStudents.DataSource = dt;
gvStudents.DataSourceID = null; // Null out the id, we have a source
gvStudents.DataBind();
//update the viewstate with the new amount of rows
ViewState["gv"] = dt;
}
}
So you can see, using a ViewState as a replacement to the SqlDataSource, you're able to manipulate the Gridview as you wish and never call the original SqlDataSource again, except the first time to get the data.
And tell your professor he's an arrogant pig.