I found the tutorial to create a dynamic table and add rows:
http://geekswithblogs.net/dotNETvinz/archive/2009/06/29/faq-dynamically-adding-rows-in-asp-table-on-button-click.aspx
How can I read all rows in the table, and then the values of the textbox in the cells? The values are entered in a table in a database (SQL Server).
Can I continue to use C# and asp.net or do I have to use Javascript?
I hope someone will give me help.
This is the code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamic Adding of Rows in ASP Table Demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" />
</form>
</body>
</html>
CODE BEHIND:
public partial class _Default1 : System.Web.UI.Page
{
//A global variable that will hold the current number of Rows
//We set the values to 1 so that it will generate a default Row when the page loads
private int numOfRows = 1;
protected void Page_Load(object sender, EventArgs e)
{
//Generate the Rows on Initial Load
if (!Page.IsPostBack)
{
GenerateTable(numOfRows);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["RowsCount"] != null)
{
numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
GenerateTable(numOfRows);
}
}
private void SetPreviousData(int rowsCount, int colsCount)
{
Table table = (Table)Page.FindControl("Table1");
if (table != null)
{
for (int i = 0; i < rowsCount; i++)
{
for (int j = 0; j < colsCount; j++)
{
//Extracting the Dynamic Controls from the Table
TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
//Use Request objects for getting the previous data of the dynamic textbox
tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
}
}
}
}
private void GenerateTable(int rowsCount)
{
//Creat the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
//The number of Columns to be generated
const int colsCount = 3;//You can changed the value of 3 based on you requirements
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
// Set a unique ID for each TextBox added
tb.ID = "TextBoxRow_" + i + "Col_" + j;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// And finally, add the TableRow to the Table
table.Rows.Add(row);
}
//Set Previous Data on PostBacks
SetPreviousData(rowsCount, colsCount);
//Sore the current Rows Count in ViewState
rowsCount++;
ViewState["RowsCount"] = rowsCount;
}
}
Since you're creating the table dynamically, you can't reference it like controls that are statically embedded on the page. To get a reference to the Table object you'll need to find it in the Page's ControlCollection and cast it out, just like in the example:
Table table = (Table)Page.FindControl("Table1");
The Table class contains a table row collection which you will then need to loop over. Each row in the row collection has a collection of cells, each of which will contain child controls (see: Controls property) which will be your textboxes.
Hi if you take look at SetPreviousData this function is trying to read previous textbox value but there is some thing wrong with it i have done following changes and it works fine
first of all the following code in SetPreviousData
Table table = (Table)Page.FindControl("Table1");
is always returning NULL because this function is not a recursive function and your table may be inside a container in your page so add following function to your code
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
and change the code
Table table = (Table)Page.FindControl("Table1");
to
Table table = FindControlRecursive(Page , "Table1") as Table;
in next step change the following code in SetPreviousData
tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
to
tb.Text = Request.Form[tb.UniqueID];
set break points and see the results if it's tough to you let me know to provide you a function which returns table data in a datatable
I think you must bind your table again at the Page_load event.For example if you are binding the table at View_Click button event,you have to call this method in Page_load event as View_Click(null,null).
<script type="text/javascript">
var StringToSend='';
function fncTextChanged(newvalueadded) {
if (StringToSend != '')
StringToSend = StringToSend + ';' + newvalueadded;
else
StringToSend = newvalueadded;
//alert(StringToSend); -- For Testing all values
// now store the value of StringToSend into hidden field ---- HFTEXTVALUES to access it from server side.
}
</script>
<asp:Button ID="Save" runat="server" onclick="SaveTextBoxValues_Click" Text="save" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" />
<asp:HiddenField ID="hfTextValues" runat="server" Visible="false" Value="" />
Server Side :
protected void Page_Load(object sender, EventArgs e)
{
//Generate the Rows on Initial Load
if (!Page.IsPostBack)
{
GenerateTable(numOfRows);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["RowsCount"] != null)
{
numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
GenerateTable(numOfRows);
}
}
protected void SaveTextBoxValues_Click(object sender, EventArgs e)
{
string AllTextBoxValues = hfTextValues.Value;
string[] EachTextBoxValue = AllTextBoxValues.Split('~');
//here you would get all values, EachTextBoxValue[0] gives value of first textbox and so on.
}
private void GenerateTable(int rowsCount)
{
//Creat the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
//The number of Columns to be generated
const int colsCount = 3;//You can changed the value of 3 based on you requirements
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
HiddenField hf = new HiddenField();
// Set a unique ID for each TextBox added
tb.ID = "tb" + i + j;
hf.ID = "hf" + i + j;
tb.Attributes.Add("onblur", "fncTextChanged(this.value);");
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// And finally, add the TableRow to the Table
table.Rows.Add(row);
}
}
Let me know if you have any questions.
One more thing, if you wish to store the values and retrieve them later, the code would be modified accordingly.
reference for a dynamic table doesn't work well , blame microsoft ,
I use this :
Save inside a session List[YourObjectData] and every time you get into Page_Load , fill it the table
here is solution for number 2 :
somewhere inside Default.aspx
<div class="specialTable">
<asp:Table ID="Table1" runat="server" />
</div>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
FillDynamicTable();
if (!IsPostBack)
{
}
}
private void FillDynamicTable()
{
Table1.Rows.Clear(); // Count=0 but anyways
if (Session["Table1"] == null) return;
foreach (var data in Session["Table1"] as List<MyObject>)
{
AddRow(data);
}
}
private void AddRow(MyObject data)
{
var row = new TableRow { Height = 50 };
var cell = new TableCell();
var label = new Label { Text = data.something, Width = 150 };
cell.Controls.Add(label);
row.Cells.Add(cell);
Table1.Rows.Add(row);
}
Related
We have a table on aspx page as -
<asp:Table ID="tblContainer" runat="server" Visible="false">
<asp:TableHeaderRow>
<asp:TableCell> Alplabates </asp:TableCell>
</asp:TableHeaderRow>
</asp:Table>
and we are adding control in this table as -
protected void Page_Load(object sender, EventArgs e)
{
int rowcount = tblContainer.Rows.Count;
// rowcount is one always
GenerateDynamicControls();
}
private void GenerateDynamicControls()
{
int rowcount = tblContainer.Rows.Count;
tblContainer.Visible = true;
for (int i = 0; i < 2; i++)
{
TableRow tr = new TableRow();
TableCell td = new TableCell();
TextBox textBox = new TextBox();
textBox.ID = i + "abc";
td.Controls.Add(textBox);
tr.Cells.Add(td);
tblContainer.Rows.Add(tr);
}
}
Table row count appears as one always. We tried by setting EnableViewState=true but no luck.
Can you please guide how can we get its value?
Thank you!
I have two buttons. One button that creates the Textbox and another that submits the information. I'm having trouble retrieving the users texts once the textbox has been created. Here is the code:
private void CreateTextBox(int j) //Creates the fields / cells
{
TextBox t = new TextBox();
t.ID = "Textbox" + j;
//t.Text = "Textbox" + j;
lstTextBox.Add(t);
var c = new TableCell();
c.Controls.Add(t);
r.Cells.Add(c);
table1.Rows.Add(r);
Session["test"] = lstTextBox;
}
protected void Button2_Click(object sender, EventArgs e)
{
string[] holder = new string[4];
for (int i = 0; i < holder.Length; i++)
{
holder[i] = "";
}
List<TextBox> lstTextBox = (Session["test"] as List<TextBox>);
if (lstTextBox.Count < Counter)
{
int i = lstTextBox.Count;
for (int j = 0; j < i; j++)
{
holder[j] = lstTextBox[j].Text;
}
SqlConnection conns = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDBConnectionString1"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into LoanerForm (field0, field1, field2, field3) Values (#field0, #field1, #field2, #field3)", conns);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#field0", holder[0]);
cmd.Parameters.AddWithValue("#field1", holder[1]);
cmd.Parameters.AddWithValue("#field2", holder[2]);
cmd.Parameters.AddWithValue("#field3", holder[3]);
conns.Open();
cmd.ExecuteNonQuery();
conns.Close();
}
Counter = 0;
Button1.Visible = true; //Going to submit data to SQL
}
Thank you in advance!
Here is how you create TextBoxes dynamically. It keeps track of the number of textboxes in ViewState.
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click"
Text="Create TextBoxes" />
<asp:Button runat="server" ID="Button2" OnClick="Button2_Click"
Text="Save TextBoxes to Database" />
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
public int Counter
{
get { return Convert.ToInt32(ViewState["Counter"] ?? "0"); }
set { ViewState["Counter"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
// Need to reload those textboxes on page back
// Otherwise, they will becomes null
int total = Counter;
for (int i = 0; i < total; i++)
{
var textBox = new TextBox
{
ID = "TextBox" + i,
Text = "TextBox" + i
};
PlaceHolder1.Controls.Add(textBox);
}
}
private void CreateTextBox(int id)
{
var textBox = new TextBox
{
ID = "TextBox" + id,
Text = "TextBox" + id
};
PlaceHolder1.Controls.Add(textBox);
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTextBox(Counter);
Counter = Counter + 1;
}
protected void Button2_Click(object sender, EventArgs e)
{
int total = Counter;
for (int i = 0; i < total; i++)
{
var textbox = PlaceHolder1.FindControl("TextBox" + i) as TextBox;
var text = textbox.Text;
// Do something with text
}
}
Don't store the TextBoxes in Session; rather, create them on the page.
The trick is creating them at the right time EVERY time (i.e. with each PostBack). Try loading them OnLoad() for the page (or CreateChildControls() if possible).
Once you do that, ASP.NET will automatically associate the input with the TextBox and you should be able to reference them as you normally would or via .FindControl() of the parent.
I think You used big program for generating dynamic textboxes and inserting into data base.For retriving text from dynamically generated textboxes,use the code below..
Request.Form["Textbox" + i.ToString()]
where "i" represents the number of textboxes you generated.
For more info.Please Check the below link.
how to insert value to sql db from dynamically generated textboxes asp.net
I am a noob and i've been trying to figure out how we may assign an ID to asp:TextBox tags on creation in ASP.NET using c#.
Example:
I need to create a thread that may have multiple textboxes.
When a user clicks on a button, a text box must be generated with an ID say, txt01. On being clicked the second time, the ID of the generated text box must be txt02 and so on..depending on the number of clicks.
Thanks in Advance.
Remember last ID in some variable, for example int lastID, then in button's onClick method when creating the new TextBox assign its ID="txt"+lastID;.
You have to persist the lastID during page postbacks, you can store it in a ViewState.
Take and placeholder in your aspx page: eg: <asp:PlaceHolder runat="server" ID="pholder" />
and in code behind:
TextBox txtMyText = new TextBox();
tb1.ID = YourDynamicId;
pholder.Controls.Add(txtMyText);
You can save current id in ViewState and get the same id and assign incremented id to your dynamic textbox.
Try This:
int i = 1;
if (ViewState["i"] == null)
{
ViewState["i"] = i;
}
else
i = (int)ViewState["i"];
PlaceHolder1.Controls.Clear();
for (int j = 1; j <= i; j++)
{
TextBox TextBox = new TextBox();
TextBox.ID = "TextBox" + j.ToString();
PlaceHolder1.Controls.Add(TextBox);
}
ViewState["i"] = i + 1;
add this on your .aspx page
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
Hope This help.
I think this is what you are looking for -
You will notice that I have used Page_Init because if you create/add the controls in Page_Load then FindControl will return null in PostBack. And also any data you entered in the dynamically added controls will not persist during Postbacks.
But Page_Init is called before ViewState or PostBack data is loaded. Therefore, you can not use ViewState or any other controls to keep the control count. So I have used Session to keep the count.
Try it out and let me know what you think.
ASPX Page
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" />
<asp:Button ID="btnRead" runat="server" Text="Read" OnClick="btnRead_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
Code Behind
protected int NumberOfControls
{
get { return Convert.ToInt32(Session["noCon"]); }
set { Session["noCon"] = value.ToString(); }
}
private void Page_Init(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
//Initiate the counter of dynamically added controls
this.NumberOfControls = 0;
else
//Controls must be repeatedly be created on postback
this.createControls();
}
private void Page_Load(object sender, System.EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
TextBox tbx = new TextBox();
tbx.ID = "txtData"+NumberOfControls;
NumberOfControls++;
PlaceHolder1.Controls.Add(tbx);
}
protected void btnRead_Click(object sender, EventArgs e)
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = (TextBox)PlaceHolder1.FindControl("txtData" + i.ToString());
//Add the Controls to the container of your choice
Label1.Text += tx.Text + ",";
}
}
private void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = new TextBox();
tx.ID = "txtData" + i.ToString();
//Add the Controls to the container of your choice
PlaceHolder1.Controls.Add(tx);
}
}
store the id in a ViewState something like this
First initialise a count variable similiar to this.
in your class write this
protected int replyCount //declare the variable
{
get { return (int)ViewState["replyCount"]; }
set { ViewState["replyCount"] = value; }
}
In your page Load write this to initialise the replyCount if its not a postback;
protected void Page_Load(object sender, EventArgs e)
{
if(!page.IsPostBack)
{
replyCount = 0; //initialise the variable
}
}
then while creating dynamic textboxes
protected void Button_Click(Object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.id = "tb" + replycount; //use the variable
replycount++; // and after using increment it.
form.controls.add(tb); // assuming your form name is "form"
}
Thats it you should do.
I need to generate 3 DropDownList Boxes in a row Dynamically on ADD Button click event. Once the DDL is generated i should be able to assign Data source to it and also do DDL-selectedEventChanged functionality on them in c# asp.net.
Below link was exactly am looking for but i couldn't assign data source or i couldn't do any functionality
"Adding multiple DropDownLists with a button click"
any better Ideas please help
if i press Button i need to get 3 DDLs at a time, if i press again it should generate again, so number of clicks= no. of rows with three DDL's in each row
Here is the sample code. The only trick is that you need to load those dynamic controls again after post back. Otherwise, you won't be able to access those.
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:Button runat="server" ID="AddButton" OnClick="AddButton_Click" Text="Add" />
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
private List<string> DataSource
{
get { return new List<string> { "One", "Two", "Three" }; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var dataSource = DataSource;
foreach (int id in ControlIds)
{
var ddl = new DropDownList();
ddl.ID = id.ToString();
foreach (var data in dataSource)
ddl.Items.Add(new ListItem(data));
PlaceHolder1.Controls.Add(ddl);
}
}
}
protected void AddButton_Click(object sender, EventArgs e)
{
var dataSource = DataSource;
for (int i = 0; i < 3; i++)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var ddl = new DropDownList();
ddl.ID = id.ToString();
foreach (var data in dataSource)
ddl.Items.Add(new ListItem(data));
PlaceHolder1.Controls.Add(ddl);
}
}
I am dynamically creating a table with data and check boxes in it, my problem is when i check to see one specific check-box is checked, out of many, it resets to the default state of false (note: its not just one it doesn't work with, it works with non of the generated check boxes)
Before i create the page_load function i create the check box, further down i create the table, and populate it with data, then i set up a function to check on a click to see if the box was indeed checked, iv'e tried many iterations of this with no luck
protected void table_builder(SqlDataReader readerinfo)
{
//Create a new step for the user
step3label.Text = "3.";
//Table header
TableHeaderRow hr = new TableHeaderRow();
TableHeaderCell hc = new TableHeaderCell();
TableHeaderCell hc2 = new TableHeaderCell();
TableHeaderCell hc3 = new TableHeaderCell();
hr.Cells.Add(hc);
hc.Text = "ID"; //Assign header 1 with a name
hr.Cells.Add(hc2);
hc2.Text = "Name";//Assign header 2 with a name
hr.Cells.Add(hc3);
hc3.Text = "Selection";
Table1.Rows.Add(hr);
//Dynamic Table Generation
int numcells = 3;
int triswitch = 0;//this is use to chose which cell is made, id, name or selection
string checkboxID = null;
while (readerinfo.Read()) //execute the following aslong as there is data to fill the table with
{
for (int j = 0; j < 1; j++)
{
TableRow r = new TableRow();
for (int i = 0; i < numcells; i++)
{
TableCell c = new TableCell();
switch (triswitch)
{
case 0: // this case sets the info for the feild id
c.Text = readerinfo.GetSqlGuid(0).ToString();
checkboxID = readerinfo.GetSqlGuid(0).ToString();
r.Cells.Add(c);
triswitch = 1;
break;
case 1:
c.Text = readerinfo.GetString(1);
r.Cells.Add(c);
triswitch = 2;
break;
case 2:
Checkbox_creator(checkboxID,ref c);
r.Cells.Add(c);
triswitch = 0;
break;
}
}
Table1.Rows.Add(r);
}
}
}
protected void Checkbox_creator(string id,ref TableCell send)
{
//create the checbox
ckbx = new CheckBox();
ckbx.ID = "CBX" + checkboxid.ToString();
checkboxid++;
ckbx.InputAttributes.Add("value", id);
send.Controls.Add(ckbx); //add the chekbox to the cell
checkboxidlist.Add(id);//add the id of the checkbox to the list
}
//
//AFTER DATATABLE IS LOADED
//
public void test()
{
// Find control on page.
CheckBox myControl1 = (CheckBox)Table1.FindControl("CBX0");
if (myControl1 != null)
{
// Get control's parent.
Control myControl2 = myControl1.Parent.Parent.Parent;
Response.Write("Parent of the text box is : " + myControl2.ID);
if (myControl1.Checked == true)
{
Response.Write("check box checked");
}
}
else
{
Response.Write("Control not found");
}
}
//on Submit button click, execute the following function
protected void Submit_Click(object sender, EventArgs e)
{
//Code to be executed
string Userinput; //declare Userinput variable
Userinput = Searchbox.Value; // Set variable to asp controll
Response.Write("<br /> <br />"+ Userinput +" <- user imput works");
ConnectToSql(Userinput);//insert what the user submitted into a query
test();
//
//
//NoTe code validation is needed to prevent injections
//
}
So basically what is happening here is that you are dynamically dropping this onto the page every time the page loads. Because you are doing this dynamically, the checkbox that fires off a "checked" event or is checked against during a postback no longer exists as it is not part of the viewstate. The way that the ASP.NET page lifecycle works is to fire off the sequence of lifecycle events regardless of whether or not the page is posted back or not, meaning that a new page is built upon you firing a postback event and the page goes through preinit, init, preload, load, and all that jazz before it actually hits any of the event handling code. The page that exists for the postback has a freshly created set of checkboxes that have no binding to the ones that were on the previous page.
You have a few options here, and here are two of them:
Have the 'checked' event fire a postback and have the unique ID of the web control checked against a collection you maintain on the server. You can drop the controls onto the page via a repeater or gridview and hook into its populate event. In doing so you can add the unique ID of the control that was just added into a Dictionary that you store in session that maintains any relationship that you want from a checkbox to a piece of data.
Use Javascript to update a hidden field that is always on the page and has view state enabled. In doing so you can have some sort of delimited string containing the information you deem relevant to the 'checked' checkboxes. Every time a checkbox is checked, add its identifying information to the hidden input field's value and then when the postback fires you should be able to check that hidden input for its value and do whatever you need to do from there.
These both seem like pretty hairy ways of handling this though. If you elaborate on what exactly you need then perhaps I can give you a better suggestion.
add the check boxes to the page before the view state is loaded and the event fires. Do it in the OnInit method not the onload. Use Onload to see if they're checked or not. Be sure you're giving them ID's. Unless this is a partial postback (ajax) then only render the check boxes if !IsPostback
It appears after two days of searching, i have found a pretty good solution that is much quicker and easier to understand than some others; It appears that as the other answers state, it is because of the page_load, however in this situation init is not needed, you simply need to recreate all of the controls before you can do anything else.
The key to this solution is:
protected void RecreatePreviousState()
{
if (this.IsPostBack)
{
//code to recreate
}
}
Where the comment in the above code is, is where you call the main function that creates all of your controls, like in my example it was:
ConnectToSql(Searchbox.Value)
below will be all of the code associated with this page, for future reference for anyone with this problem.
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class codebehind : System.Web.UI.Page
{
//DECLARATIONS
string selectedvalue;
List<string> createdckbxs = new List<string>();
List<string> CheckedCheckboxes = new List<string>();
CheckBox ckbx;
int ckbxID = 0;
//END DECLARATIONS
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now); //local time -- testing
Response.Write("<br /><br />NOTE: the id feild in the below table will be useless soon, it is only for testing purposes, look at CRM<br /><br />");
selectedvalue = Request.QueryString["filter"];
//88888888888888888
RecreatePreviousState();
//88888888888888888
Response.Write(selectedvalue);
instructionsfunc();
}
protected void instructionsfunc()
{
switch (selectedvalue)
{
case "Name":
instructions.Text = "Please enter the first few letters of the company you are looking for, ex. for "some company", you might search som";
break;
case "State":
instructions.Text = "Please enter the abreviation of the state you are looking for, ex. for New York, enter NY";
break;
}
}
protected string sqlSelector(string uinput)
{
switch (selectedvalue) //create the sql statments
{
case "Name":
return "SELECT [id],[name] FROM [asd].[jkl] WHERE [name] LIKE '" + uinput + "%' and [deleted] = 0 ORDER BY [name] ASC";
case "State":
return "SELECT [id],[name] FROM [asd].[jkl] WHERE [shipping_address_state] LIKE '" + uinput + "%' and [deleted] = 0 ORDER BY [name] ASC";
default:
Response.Redirect("errorpage.aspx?id=002");
return null;
}
}
//on Submit button click, execute the following function NOTE THIS BUTTON's ONLY USE IS POSTBACK
protected void Submit_Click(object sender, EventArgs e)
{
string Userinput; //declare Userinput variable
Userinput = Searchbox.Value; // Set variable to asp controll
Response.Write("<br /> <br />"+ Userinput +" <- user imput works");
}
//on Clear button click execute the following function
protected void Clear_Click(object sender, EventArgs e)
{
Response.Redirect(Request.RawUrl);
}
protected void ConnectToSql(string input)
{
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
//Todo add any aditional data needed to connection
conn.ConnectionString = ConfigurationManager.ConnectionStrings["SplendidTestConnectionString"].ConnectionString;
try
{
conn.Open();
//this is the actual sql, this gets the data
SqlCommand sqlString2 = new SqlCommand();
sqlString2.CommandText = sqlSelector(input);
sqlString2.CommandTimeout = 15;
sqlString2.CommandType = System.Data.CommandType.Text;
sqlString2.Connection = conn;
SqlDataReader reader;
reader = sqlString2.ExecuteReader();
table_builder(reader);
reader.Close(); //close the sql data reader
}
catch (Exception e)
{
//Some sort of redirect should go here to prevent the user from vewing a broken page
conn.Close();
//Response.Redirect("errorpage.aspx?id=001");
Response.Write(e);
}
finally
{
if (conn.State != System.Data.ConnectionState.Closed)
{
conn.Close();//close up the connection after all data is done being populated
}
}
}
protected void table_builder(SqlDataReader readerinfo)
{
//Create a new step for the user
step3label.Text = "3.";
//Table header
TableHeaderRow hr = new TableHeaderRow();
TableHeaderCell hc = new TableHeaderCell();
TableHeaderCell hc2 = new TableHeaderCell();
TableHeaderCell hc3 = new TableHeaderCell();
hr.Cells.Add(hc);
hc.Text = "ID"; //Assign header 1 with a name
hr.Cells.Add(hc2);
hc2.Text = "Name";//Assign header 2 with a name
hr.Cells.Add(hc3);
hc3.Text = "Selection";
Table1.Rows.Add(hr);
//Dynamic Table Generation
int numcells = 3;
int triswitch = 0;//this is use to chose which cell is made, id, name or selection
while (readerinfo.Read()) //execute the following aslong as there is data to fill the table with
{
for (int j = 0; j < 1; j++)
{
TableRow r = new TableRow();
for (int i = 0; i < numcells; i++)
{
TableCell c = new TableCell();
switch (triswitch)
{
case 0: // this case sets the info for the feild id
c.Text = readerinfo.GetSqlGuid(0).ToString();
//RENAME THIS To ADDING BUTTON = readerinfo.GetSqlGuid(0).ToString();
r.Cells.Add(c);
triswitch = 1;
break;
case 1:
c.Text = readerinfo.GetString(1);
r.Cells.Add(c);
triswitch = 2;
break;
case 2:
ckbx = new CheckBox();
ckbx.ID = "CBX" + ckbxID;
createdckbxs.Add(ckbx.ID);
c.Controls.Add(ckbx);
r.Cells.Add(c);
triswitch = 0;
ckbxID++;
break;
}
}
Table1.Rows.Add(r);
}
}
}
//
//AFTER DATATABLE IS LOADED
//
protected void RecreatePreviousState()
{
if (this.IsPostBack)
{
ConnectToSql(Searchbox.Value);
MergeBtnCreate();
}
}
protected void MergeBtnCreate()
{
Button MergeBTN = new Button();
MergeBTN.Text = "Merge";
MergeBTN.Click += new EventHandler(MergeBTN_Click);
MergeBTNHolder.Controls.Add(MergeBTN);
}
void MergeBTN_Click(object sender, EventArgs e)
{
foreach(string id in createdckbxs)
{
CheckBox myControl1 = (CheckBox)Table1.FindControl(id);
if (myControl1 != null)
{
if (myControl1.Checked == true)
{
CheckedCheckboxes.Add(id);
}
}
else
{
Response.Redirect("errorpage.aspx?id=003");
}
}
}
}
Asp.net
<%# Page Language="C#" AutoEventWireup="true" CodeFile="codebehind.aspx.cs" Inherits="codebehind" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Hello</title>
</head>
<body>
<form id="form1" runat="server">
<div style="background-color:#55aaff;margin-bottom:10px;padding:5px;">
<h3 style="padding:2px;margin:0px;">
2.
</h3>
<asp:Label ID="instructions" runat="server" />
<asp:Label ID="buttonclicked" runat="server" />
<br />
<input id="Searchbox" type="text" runat="server" />
<br />
<asp:Button ID="SubmitBTN" runat="server" OnClick="Submit_Click" Text="Submit" />
<asp:Button ID="ClearBTN" runat="server" OnClick="Clear_Click" Text="Clear" />
</div>
<div>
<h3 style="padding:2px;margin:0px;">
<asp:Label ID="step3label" runat="server" Text=""></asp:Label>
</h3>
<asp:Table ID="Table1" runat="server" GridLines="Both" />
</div>
<div>
<asp:PlaceHolder ID="MergeBTNHolder" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>