I am trying to code a survey application which requires text boxes to be added and removed dynamically. I managed to create text boxes dynamically on button click but I'm trying to find out how to removed the text boxes dynamically. Currently the delete functions works well only if I remove text boxes starting from the last. When I try deleting any text boxes in the middle followed by a delete of the last text box, a blank text box is created instead. I'm new to programming and am unsure if this is the best method to use. Also, I would like to find out if it is possible to nest text boxes(allow users to add options to their multi choice questions) to created text boxes and retrieve values inside later.
Code behind:
public partial class Dynamic_Form : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < TotalNumberAdded; ++i)
{
AddQuestion(i + 1);
}
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void btn_add_Click(object sender, EventArgs e)
{
TotalNumberAdded++;
AddQuestion(TotalNumberAdded);
}
private void AddQuestion(int controlNumber)
{
Panel newquestion = new Panel();
newquestion.ID = "Panel_" + controlNumber;
TextBox questionbox = new TextBox();
questionbox.ID = "Question_" + controlNumber;
questionbox.Text = "Question";
Button BtnDelete = new Button();
BtnDelete.ID = "BtnDelete_" + controlNumber;
BtnDelete.Text = "Delete"+ controlNumber;
BtnDelete.Click += delete_Click;
DropDownList DDLType = new DropDownList();
DDLType.ID = "DDLType_" + controlNumber;
DDLType.Items.Insert(0, new ListItem("TextField", ""));
DDLType.Items.Insert(1, new ListItem("Multiple Choice", ""));
//add controls
questions.Controls.Add(newquestion);
newquestion.Controls.Add(questionbox);
newquestion.Controls.Add(DDLType);
newquestion.Controls.Add(BtnDelete);
}
private void delete_Click(object sender,EventArgs e)
{
Button btn = (Button)sender;
Control control = btn.Parent;
if (questions.Controls.Contains(control))
{
questions.Controls.Remove(control);
control.Dispose();
TotalNumberAdded--;
Response.Write("Number of Questions:" + TotalNumberAdded);
}
}
}
Html file:
<body>
<form id="form1" runat="server">
<div>
<h1>Test Form</h1>
<asp:Button ID="btn_add" runat="server" Text="Add" OnClick="btn_add_Click" />
</div>
<div id="questions" runat="server">
</div>
</form></body>
.
#Aaron Yong, You can do these scenarios from client side using jQuery or javascript too. I have given below code to achieve what you want from server side.
private void delete_Click(object sender,EventArgs e)
{
Button btn = (Button)sender;
Control control = btn.Parent;
if (questions.Controls.Contains(control))
{
TotalNumberAdded--;
questions.Controls.Clear();
for (int i = 0; i < TotalNumberAdded; ++i)
{
AddQuestion(i + 1);
}
Response.Write("Number of Questions:" + TotalNumberAdded);
}
}
You want to recreate controls again, i have added for loop and removed some code in delete click event, then you will achieve.
As i have given above answer, you can also remove below code from previous answered.
questions.Controls.Remove(control);
control.Dispose();
You will get exact answer
Related
I have a problem with asp.net event system.
As the page is being loaded for the first time, a DropDownList is being populated and that's it. On the list SelectedIndexChange the page does a page postback and loads some more info, dynamically creating buttons for it based on some data taken out from the DB.
And at this point all works as expected, the CustomDivs are created and displayed correctly. The problems happens when i click on one of the dynamically created buttons, the page does the postback, goes trouhg the page load but never enters the method of the button that was clicked.
Looking around in the internet i read something about event handlers must be created in the Page_Load method to registered. So i even modified the code behind so that the CaricaPostazioni() method would be fired in the Page_Load, but that did not work. I also tried some other stuff like AutoPostBack property or UseSubmitBheaviour or CausesValidation but nothing seems to work as expected.
I should say that this page is a content page of master page that does absolutely nothing in it's Page_Load()
Any one can help me in this matter? Thank you very much!
Here is the code behind of assegnapostazione.aspx
using Industry4_camerana_gruppo1.App_Code;
using Industry4_camerana_gruppo1.App_Code.Dao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Industry4_camerana_gruppo1 {
public partial class assegnapostazione : System.Web.UI.Page {
static List Macchinisti = null;
protected void Page_Load(object sender, EventArgs e) {
if (Macchinisti == null) {
Macchinisti = new daoUtente().GetByRuolo("macchinista");
drp_Macchinisti.Items.Add(new ListItem("Seleziona...", "-1"));
foreach (Utente U in Macchinisti) {
drp_Macchinisti.Items.Add(new ListItem(U.Username, U.ID.ToString()));
}
}
}
public void CaricaPostazioni() {
//if (drp_Macchinisti.SelectedValue == "-1") return;
int IDUtente = Convert.ToInt32(drp_Macchinisti.SelectedItem.Value);
List Postazioni = new daoPostazioni().GetAll();
Dictionary Relazioni = new daoPostazioni().GetUtentePostazioni(IDUtente);
if (Postazioni != null) {
Panel row = new Panel();
row.CssClass = "row";
int i = 0;
foreach (Postazione p in Postazioni) {
if (i % 4 == 0) {
pnl_Postazioni.Controls.Add(row);
row = new Panel();
row.CssClass = "row";
}
if (Relazioni.ContainsKey(p.ID)) {
row.Controls.Add(CustomDiv(p, IDUtente, true));
} else {
row.Controls.Add(CustomDiv(p, IDUtente, false));
}
i++;
}
pnl_Postazioni.Controls.Add(row);
}
}
public Panel CustomDiv(Postazione P, int IDUtente, bool Assegnato) {
//
//
//
//
// Foratura
//
//
//
Panel wrapper = new Panel();
wrapper.CssClass = "col";
Panel card = new Panel();
card.CssClass = "card text-center postazione form-group";
Image img = new Image();
img.CssClass = "mx-auto d-block width-70";
img.ID = "btn_" + P.ID;
img.ImageUrl = "~/imgs/ic" + P.Tipo + ".png";
Panel cardTitle = new Panel();
cardTitle.CssClass = "card-title";
Label title = new Label();
title.Text = P.Tipo.ToUpper() + " - " + P.Tag;
Button btn = new Button();
//btn.ID = "btn_" + P.ID + IDUtente;
btn.Attributes.Add("PID", P.ID.ToString());
btn.Attributes.Add("UID", IDUtente.ToString());
//btn.UseSubmitBehavior = true;
if (Assegnato) {
btn.Click += new EventHandler(btn_Rimuovi_Click);
//btn.Click += delegate {
// btn_Rimuovi_Click(btn, null);
//};
btn.CssClass = "btn btn-warning mx-auto form-control";
btn.Text = "Rimuovi";
} else {
btn.Click += new EventHandler(btn_Assegna_Click);
//btn.Click += delegate {
// btn_Assegna_Click(btn, null);
//};
btn.CssClass = "btn btn-success mx-auto form-control";
btn.Text = "Assegna";
}
card.Controls.Add(img);
cardTitle.Controls.Add(title);
card.Controls.Add(cardTitle);
card.Controls.Add(btn);
wrapper.Controls.Add(card);
return wrapper;
}
protected void drp_Macchinisti_SelectedIndexChanged(object sender, EventArgs e) {
CaricaPostazioni();
}
protected void btn_Rimuovi_Click(object sender, EventArgs e) {
Button btn = (Button)sender;
new daoPostazioni().AddRelazione(Convert.ToInt32(btn.Attributes["UID"]), Convert.ToInt32(btn.Attributes["PID"]));
}
protected void btn_Assegna_Click(object sender, EventArgs e) {
Button btn = (Button)sender;
new daoPostazioni().DeleteRelazione(Convert.ToInt32(btn.Attributes["UID"]), Convert.ToInt32(btn.Attributes["PID"]));
}
}
}
Well, I have an answer for you but I don't think you are going to like it.
Due to the stateless nature of webforms, any controls that you add dynamically to a form on a postback will also need to be added back to the page and have it's server events rebound during the OnInit event.
I've created a minimal example that can demonstrate what's going on with this behavior so you can better understand what's happened.
ButtonTest.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ButtonTest.aspx.cs" Inherits="ButtonTest.ButtonTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form runat="server">
<asp:Panel runat="server" ID="ButtonPanel">
<asp:Button runat="server" ID="ButtonAdd" OnClick="ButtonAddClick" Text="Click Me"></asp:Button>
</asp:Panel>
</form>
</body>
</html>
And the code behind:
ButtonTest.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace ButtonTest
{
public partial class ButtonTest : System.Web.UI.Page
{
static List<Button> buttons = new List<Button>();
static bool allowItToWork = true;
protected override void OnInit(EventArgs e)
{
if(Page.IsPostBack && allowItToWork)
{
foreach (var button in buttons)
{
button.Click += ButtonAddClick; // Comment me out and added button's will do nothing when clicked.
ButtonPanel.Controls.Add(button);
}
}
}
protected void ButtonAddClick(object sender, EventArgs e)
{
var button = new Button();
button.Click += ButtonAddClick;
button.Text = "Click Me Too";
buttons.Add(button);
ButtonPanel.Controls.Add(button);
}
}
}
You can toggle between desirable and undesirable behavior by changing the value of the allowItToWork boolean.
When it's set to true, the OnInit overload is adding all buttons back onto the page, as well as applying their event handlers again, because those handlers seem to be lost during the PostBack (unsure on why this happens.) You can click away and new buttons will be added onto the form forever and ever.
When it's set to false, the added button will appear whenever you click the initial button, but it won't fire an event handler as it's no longer bound, and clicking the original button repeatably won't continue to add additional buttons, you'll only ever see a single one, and that one will disappear on PostBack if clicked.
So, the end result of this is essentially that you're stuck reconstructing the whole shebang in the OnInit event.
Within a web form I am dynamically creating a series of chekboxes that are added to an asp:panel.Where as the panel in reside into a update panel.I want to avoid postback on checkbox changed event fire.
my code snippet:
Aspx code:
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlCuisine" runat="server"></asp:Panel>
</ContentTemplate>
C# Code:
public static CheckBox[] chkbx = new CheckBox[15];
public static Label[] lblCuisine = new Label[15];
private void LoadCuisine(string searchStr)
{
.....
.....
.....
int i = 1;
foreach(var item in cuisineList)
{
chkbx[i]=new CheckBox();
chkbx[i].ID = item.CategoryName;
chkbx[i].Text = item.CategoryName;
chkbx[i].AutoPostBack = true;
lblCuisine[i] = new Label();
lblCuisine[i].ID = "lblCuisine" + Convert.ToString(i);
lblCuisine[i].Text = "(" + item.Count + ")";
chkbx[i].CheckedChanged += new EventHandler(chkbx_CheckedChanged);
pnlCuisine.Controls.Add(chkbx[i]);
pnlCuisine.Controls.Add(lblCuisine[i]);
pnlCuisine.Controls.Add(new LiteralControl("<br/>"));
i++;
}
}
void chkbx_CheckedChanged(object sender, EventArgs e)
{
string searchString = ((CheckBox)sender).ClientID;
populateGrid(searchString);
}
Please change this line of code
chkbx[i].AutoPostBack = true;
to
chkbx[i].AutoPostBack = false;
then you can avoid auto post back on checkbox changed event fire
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 am doing following code to generate dynamic buttons with their click event.
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
Button bt = new Button();
bt.Text = "ok";
bt.Click += new EventHandler(bt_click);
this.form1.Controls.Add(bt);
}
}
protected void bt_click(object sender, EventArgs e)
{
Label1.Text = "Clicked";
}
but i am not able to generate the click event of that dynamically generated button.
Can any one help me?
For ASP.NET to be able to execute your event, control which triggered it should also exist on your page after postback. What is going on with your code looks like this:
page has several buttons you placed in design mode
you click button which generates new buttons
page loads again and looks for button you clicked, in the page
button is found, asp looks for event handler and executes it
new dynamic buttons are added and events attached, page renders again
It was all ok up till now, now problem occurs
you click button which was added dynamically
page loads again and looks for button you clicked (so it can find it's handler)
button is not found because it is not created yet. it was created dynamically to be rendered, and it wasn't created after postback at stage where asp is looking for it
General rule is that if you're adding controls dynamically and you want them to trigger events, you should do it latest in Page_Load.
For more details please read ASP.NET Page Life Cycle Overview
My previous submission was on WinForms which I have deleted. Here is the one on asp.net
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
CreateButton(i);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void bt_click(object sender, EventArgs e)
{
Button btn = sender as Button;
Label1.Text = btn.Text + " Clicked";
}
private void CreateButton(int id)
{
Button bt = new Button();
bt.Text = "ok" + id.ToString();
bt.Click += new EventHandler(bt_click);
bt.ID = "btn" + id.ToString();
this.Form.Controls.Add(bt);
}
You need to set the position of those new buttons, or they will cover each other.
I'm not sure if its your problem, but you might want to set the location property of eachbutton you add like:
bt.Location = new Point(25,i+55);
you need to add this code in either page load or page_init event of page. then only you can access it. How to add controls dynamically asp.net
protected void Page_Load()
{
for (int i = 0; i < int.Parse(textBox1.Text); i++)
{
Button bt = new Button();
bt.Text = "ok";
bt.Click += new EventHandler(bt_click);
this.Controls.Add(bt);
}
}
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>