storing the value of dynamically created textbox in session - asp.net

I have done a project in ASP.Net that asks to input a number in textbox. After typing a number in it and click a button it generates the number of textbox according to the value given in the textbox. Like if I type 5 in the textbox it dynamically generates 5 textboxes below.
I want all the value of dynamically created textbox(more than one textbox) to be stored in session and pass to next page through session after clicking another button. But i could not do that.
How can i solve this problem.
Anyone can help me.
Thanks

You could create an array with the values and store that in the session. Code below is untested, but should give you an idea.
string[] arrayTextboxes = new string[numberOfTextboxes];
int index = 0;
foreach (Control ctrl in Page.Controls)
{
if (ctrl is TextBox)
{
arrayTextboxes[index] = ((Textbox)ctrl).Text;
index++;
}
}
Session["tbValues"] = arrayTextboxes;

Related

how to dynamically add rows to a GridView through a DataTable without affecting any table?

I have to show a gridview in my page which doesn't concerns any table to be bound with it. Still it should store one Tax detail per row, as entered by user. Following is the image which will clarify what problem I'm facing.
The gridview shown above should not show any records at first except the footer template of two textboxes and an Add New Record Button, when you are upto add any record.
Once clicked on Add New Record button it should show a row without action column.
(I'm having quite a hard time here)Once clicked on Add/Insert Button(separate from the gridview) store the entered record somehow.
Then I have to show the record in Another concrete GridView with Edit Button.
Once I click on edit button, control should return to my dynamic gridview page. Here, my dynamic gridview will show previously entered record with action column containing a delete button.
Can you Help Me? I don't want help with the code. Just point me in the right direction(s), please.
You should try this.
private DataTable AddEmptyRow()
{
DataTable originalDataTable = GetItems();
DataTable newDataTable = originalDataTable.Clone();
string category = originalDataTable.Rows[0][2].ToString();
foreach (DataRow dRow in originalDataTable.Rows)
{
if (category != dRow[2].ToString())
{
DataRow newDataRow = newDataTable.NewRow();
newDataTable.Rows.Add(newDataRow);
category = dRow[2].ToString();
}
newDataTable.ImportRow(dRow);
}
return newDataTable;
}
You can add row by using DataRow newDataRow = newDataTable.NewRow();.

Dynamic Textbox Using Asp.net

in asp.net TextBox will create pressure to button1's. Button2 to the pressure inside the TextBox data consisting of label1 my yazdırıca. I tried to do it like this gives an error.
Object reference not set to an instance of an object.
button1_click{
TextBox txt = new TextBox();
txt.ID = "a";
txt.EnableViewState = true;
Panel1.Controls.Add(txt);
}
Button2_click{
TextBox deneme= Panel1.FindControl("a") as TextBox;
Label1.Text = deneme.Text;
}
After you create your control, on the first click, the control shown on the page and exist.
On the second click the page is not know any more about that text control because you did not save that information somewhere and because only you know that some time in the past you create it.
So on this code you have:
Button2_click{
TextBox deneme= Panel1.FindControl("a") as TextBox;
// here the deneme is null ! and you get the exception !
// the deneme is not exist on the second click, not saved anywhere
Label1.Text = deneme.Text;
}
The solution is to keep on viewstate what control you create and how, and re-create them on PageInit. Alternative you can redesign your page and think a different approach to that, eg you can have the TextControl's all ready on page hidden, and just open them.
Button2_click{
TextBox txt = (TextBox)Panel1.FindControl("a");
Label Label1 = new Label();
Label1.Text=txt.Texxt;
}

How to retrieve TextBox value in ViewState from its ID

I am building many textboxes programmatically in my ASP.NET page, after I've clicked a button, I would like to process those values, is there any possibility to retrieve them from their ID in ViewState ?
Here is my code :
Reference of the table in the aspx :
<asp:Table ID="Distances" runat="server" ViewStateMode="Inherit"></asp:Table>
Then in code behind after creating all the rows and cells, I add a textbox into some of them :
Distances.Rows[j].Cells[i].Controls.Add(CreateTB(distance.ToString(), (i + j * rows).ToString(), false));
protected TextBox CreateTB(string text, string id, bool ebanled = true)
{
TextBox tb = new TextBox() { Text = text, ID = id, Enabled = ebanled};
tb.TextChanged += new EventHandler(OnTBChanged);
return tb;
}
ViewState is enabled by default, so it should already work that the Text property is persisted across postbacks.
So you could for example use FindControl("TextBoxID") or enumerate them to get the refernce to the TextBox (assuming that they are added to a container-control like Panel):
foreach(TextBox txt in MyPanel.Controls.OfType<TextBox>())
{
String text = txt.Text;
}
or
TextBox txt = (TextBox)MyPanel.FindControl("TextBox1")
String text = txt.Text;
I assume you're not recreating those TextBoxes on postbacks. Therefore you need to use the same ID as before and recreate them in Page_Load at the latest stage in page's life-cycle. So you can create them in an event, but you cannot recreate them there.
You should show your code where you create them dynamically, then i could be more specific.
TRULY UNDERSTANDING DYNAMIC CONTROLS

Getting data from GridView on Button_Click

My problem is:
I have a GridView, which is bound to list of declared DTO objects with column of CheckBoxes. Also, I have a "Save" button on the page. My mission concludes in getting all rows, where CheckBox is checked and get the containing data. Unfortunately, row.DataItem = null on Button1_Click, because, I'm using if(!IsPostBack) gw.DataBind() statement (otherwise, I can't get CheckBox status). Could you give me the best practice for solving my problem?
Thank you in advance!
If you do if(!IsPostBack) --> gw.DataBind(), that will reinitialize your GridView and the checkboxes will be set to unchecked again.
In your case, in Button1_Click event, you can loop through each DataRow on your GridView and find the row which has it's checkbox checked and get all the selected row data.
foreach (GridViewRow gvRow in gw.Rows) {
// Find your checkbox
CheckBox chkBox = (CheckBox)gvRow.FindControl("checkBox");
if (chkBox.Checked) {
// Get your values
string value1 = gvRow.Cells[1].Text;
string value2 = gvRow.Cells[2].Text;
// etc...
}
}

ASP GridView All Rows In Edit Mode

In my ASP.NET page, I'm using a GridView to view data (Items & their prices). Currently users can edit the data (prices) in the grid row by row. (Click --> "Edit" link, change the values then "Update"). This is ROW by ROW. Is it possible to open all rows in Edit mode & use a single button (eg. Submit) to update all data once?
If you don't need to read only mode, in that case you can put input boxes ( textbox, dropdownlist, etc.) in ItemTEmplate section and bind them with existing data.
Next, put a submit button at above/below of the GridView and handle button Click event and loop through the GridView item data and save all database.
I'll post code block if you need. Thanks for your time.
And you will have better control on that you doing by using listview instead of gridview.
My best practise is using listview and custom web user control for this kind of problems.
If you fill your listview with your user control, you will easy to manage your saving method, just have to iterate on the listview items, find control and call your Save() method for each item.
I know that this question has already been answered but here is the code for loop through the GridView getting data and store it in the Data Base:
Using libraries:
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data.Odbc;
Code Behind:
// this is a variable that have the Query or SQL Commands.
string DataBaseQuery = "UPDATE [table] SET [variable2] = #variable2, [variable3] = #variable3) WHERE [variable1] = #variable1";
//Click Event from a LinkButton.
protected void LinkButton1_Click(object sender, EventArgs e)
{
//"ConnectionString" its the string connection for your DataBase (often get from the WebConfig File or a DataSource element.
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
//this is for open the database using the string connection.
connection.Open();
//this is the algorithm for going through the entire GridView.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//"DataBaseQuery" it's a string variable that have the Query or SQL Commands.
SqlCommand cmd = new SqlCommand(DataBaseQuery, conexion);
//this case it's for obtain the text variable of the first column of the gridview (in my case it was the ID of the register).
cmd.Parameters.AddWithValue("#variable1", ((Label)GridView1.Rows[i].Cells[0].FindControl("Label1")).Text.ToString());
//this case it's for obtain the selected value of a DropDownList that were in the 14 th column)
cmd.Parameters.AddWithValue("#variable2", ((DropDownList)GridView1.Rows[i].Cells[15].FindControl("DropDownlist2")).SelectedValue.ToString());
//this command it's for obtain the text of a textbox that is in the 15 th column of the gridview.
cmd.Parameters.AddWithValue("#variable3", ((TextBox)GridView1.Rows[i].Cells[16].FindControl("TextBox17")).Text.ToString());
cmd.ExecuteNonQuery();
}
//after going through all the gridview you have to close the connection to the DataBase.
connection.Close();
}
}
Of course you have to adjust the code to your particular case but it's very easy. In this code you have the example to obtain values for other object like labes, textbox and dropdownlist in the gridview.
I suffered a lot to make run this code (I'm not good programming) but I'm happy to help.
NOTE: For count the columns of the gridview you have to start at zero.
NOTE2: Sorry for my bad English by the way... It's not my nature language.

Resources