public partial class Questions : System.Web.UI.Page
{
private bool InstanceFieldsInitialized = false;
private Questions()
{
if (!InstanceFieldsInitialized)
{
InitializeInstanceFields();
InstanceFieldsInitialized = true;
}
}
private void InitializeInstanceFields()
{
r = User.Identity.Name;
}
private ArrayList #params = new ArrayList();
string r;
private ArrayList pklist = new ArrayList();
//Dynamically Loads the Questions based off of the table.
protected void Page_Load(object sender, System.EventArgs e)
{
//Questions Loaded
string proc = "Question_Select";
SqlConnection QuestionsConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Feedback-ConnectionString"].ConnectionString);
SqlCommand QuestionsCommand = new SqlCommand(proc, QuestionsConnection);
QuestionsCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(QuestionsCommand);
DataTable vTable = new DataTable();
da.Fill(vTable);
Table detailsTable = new Table();
detailsTable.CellSpacing = 10;
var i = 0;
foreach (DataRow row in vTable.Rows)
{
var value = vTable.Rows[i][0].ToString();
TableRow tRow = new TableRow();
TableCell tCell1 = new TableCell();
TableCell tCell2 = new TableCell();
var pk = vTable.Rows[i][1].ToString();
pklist.add(pk);
Label myLabel = new Label();
myLabel.CssClass = "bold";
TextBox myText = new TextBox();
myText.TextMode = TextBoxMode.MultiLine;
myText.Columns = 40;
myText.Rows = 4;
myText.ID = "Box" + i;
#params.add(myText.ID);
myLabel.Text = string.Format("{0}. {1}", i + 1, value);
tCell1.Controls.Add(myLabel);
tCell2.Controls.Add(myText);
tRow.Cells.Add(tCell1);
tRow.Cells.Add(tCell2);
detailsTable.Rows.Add(tRow);
i += 1;
}
Panel1.Controls.Add(detailsTable);
}
//INSTANT C# WARNING: Strict 'Handles' conversion only applies to fields declared in the same class - the event will be wired in 'SubscribeToEvents':
//ORIGINAL LINE: Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
protected void Button1_Click(object sender, EventArgs e)
{
//When a survey is completed, this method checks to see who completed the survey and insert them into a table.
string proc2 = "User_Insert";
SqlConnection ResponsesConnection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Feedback-ConnectionString"].ConnectionString);
SqlCommand ResponsesCommand2 = new SqlCommand(proc2, ResponsesConnection2);
ResponsesCommand2.CommandType = CommandType.StoredProcedure;
ResponsesCommand2.Parameters.AddWithValue("#UserName", r);
ResponsesConnection2.Open();
ResponsesConnection2 = (SqlConnection)ResponsesCommand2.ExecuteScalar();
// Establish connection and set up command to use stored procedure
string proc = "Responses_Insert";
SqlConnection ResponsesConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Feedback-ConnectionString"].ConnectionString);
SqlCommand ResponsesCommand = new SqlCommand(proc, ResponsesConnection);
ResponsesCommand.CommandType = CommandType.StoredProcedure;
ResponsesConnection.Open();
<--HERE IS WHERE I THINK THE PROBLEM IS-->
***var i = 0;
for (int a = 0; a < #params.ToString().Count(); a++)
{
ResponsesCommand.Parameters.Clear();
TextBox textbox = Panel1.FindControl(#params.ToString().ElementAt(a).ToString()) as TextBox;
ResponsesCommand.Parameters.AddWithValue("#QuestionID", pklist.ToString().ElementAt(i).ToString());
ResponsesCommand.Parameters.AddWithValue("#response", textbox.Text);
ResponsesCommand.Parameters.AddWithValue("#UserName", r);
ResponsesConnection = (SqlConnection)ResponsesCommand.ExecuteScalar();
i += 1;***
}
Microsoft.VisualBasic.Interaction.MsgBox("Thank you for completing the survey.", Microsoft.VisualBasic.MsgBoxStyle.MsgBoxSetForeground, "Survey Complete");
Response.Redirect("../../../Default.aspx");
}
//Button to see if a person has chosen to be marked annonymous.
//INSTANT C# WARNING: Strict 'Handles' conversion only applies to fields declared in the same class - the event will be wired in 'SubscribeToEvents':
//ORIGINAL LINE: Protected Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles Checkbox1.CheckedChanged
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (Checkbox1.Checked == false)
{
r = User.Identity.Name;
}
else
{
r = "Anonymous";
}
}
}
}
I need a little help. My code shows double output when ran. Had multiple choices to use var, object, or dynamic using code converters. Chose var but it still outputs double. When debugger is ran shows no errors.
I would question whether you need .ToString() in the following (in the for loop):
a < #params.ToString().Count()
It seems like you probably just want the number of items in the #params list, so try replacing the above with the following:
a < #params.Count
That may fix your problem of the loop executing the wrong number of times. If so, then similarly within the loop body you probably shouldn't be using .ToString() in either of these:
#params.ToString().ElementAt(a)
pklist.ToString().ElementAt(i)
If your loop still seems to be executing too many times, then you should try stepping through it in the debugger or adding print statements (Console.WriteLine) to print the variable values for each iteration of the loop and better understand what it's doing.
Related
Timer1 not start when add new User Control.I have 1 User Control (UC_Machine).And when load Form Main I using timer execute SQL query in query variable to get data from table [tbl_FF_Trigger]
I have 1 User Control (UC_Machine).And when load Form Main I using timer execute SQL query in query variable to get data from table [tbl_FF_Trigger]
-Code in UC_Machine:
private void UC_Machine_Load(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
string query = "SELECT CRDName, PartNumber ,DefectName FROM [tbl_FF_Trigger] where Machine = '" + Machine + "'";
db.fillDataGridView(query, dataGridView1);
dataGridView1.BackgroundColor = Color.White;
dataGridView1.RowHeadersVisible = false;
dataGridView1.Update();
dataGridView1.Refresh();
}
Code in form MAIN. Will get the information of the machines from the function Machine_Infor.GetMachine_Infors(). It will then create a UC_Machine array from that information. If the machine in the array does not already exist in the panellayout, it will be added to the panellayout.
In addition, it also checks if the machine exists in the tbl_FF_Trigger table. Otherwise it will delete the machine from the panellayout.
private void Main_Load(object sender, EventArgs e)
{
Get_Infor();
}
private void Get_Infor()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 3000; // Thời gian chạy (5000 milliseconds = 5 second)
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
// Add new item to panellayout if machine have falsecall
var data = Machine_Infor.GetMachine_Infors();
var list = new UC_Machine[data.Count];
int i = 0;
itemFoods = new List<UC_Machine>();
itemFoodsFilter = new List<UC_Machine>();
HashSet<string> existingMachine = new HashSet<string>();
foreach (var item in data)
{
if (!existingMachine.Contains(item.Machine))
{
bool isExisting = false;
foreach (UC_Machine uc in myFlowLayoutPanel1.Controls)
{
if (uc.Machine == item.Machine)
{
isExisting = true;
break;
}
}
if (!isExisting)
{
list[i] = new UC_Machine();
list[i].CRDName = item.CRDName;
list[i].Model = item.Model;
list[i].Machine = item.Machine;
list[i].PartNumber = item.PartNumber;
list[i].Workcell = item.Workcell;
list[i].CRDName = item.CRDName;
list[i].Date = item.Date;
itemFoods.Add(list[i]);
itemFoodsFilter.Add(list[i]);
existingMachine.Add(item.Machine);
i++;
}
}
}
if (myFlowLayoutPanel1.InvokeRequired)
{
myFlowLayoutPanel1.Invoke((MethodInvoker)delegate
{
myFlowLayoutPanel1.Controls.AddRange(list.Where(x => x != null).ToArray());
});
}
else
{
myFlowLayoutPanel1.Controls.AddRange(list.Where(x => x != null).ToArray());
}
// Remove machine if Falsecall not found
string maincon = ConfigurationManager.ConnectionStrings["Connstring"].ConnectionString;
// Connect to the SQL Server database and execute the query to check for the existence of "vnhcmsleaoi05" in the "tbl_FF_Trigger" table.
using (SqlConnection connection = new SqlConnection(maincon))
{
connection.Open();
foreach (UC_Machine uc in myFlowLayoutPanel1.Controls)
{
string query = "SELECT COUNT(*) FROM tbl_FF_Trigger WHERE Machine = '"+ uc.Machine+"'";
using (SqlCommand command = new SqlCommand(query, connection))
{
int count = (int)command.ExecuteScalar();
if (count == 0)
{
if (myFlowLayoutPanel1.InvokeRequired)
{
myFlowLayoutPanel1.Invoke((MethodInvoker)delegate
{
myFlowLayoutPanel1.Controls.Remove(uc);
itemFoods.Remove(uc);
uc.Dispose();
});
}
else
{
myFlowLayoutPanel1.Controls.Remove(uc);
itemFoods.Remove(uc);
uc.Dispose();
}
break;
}
}
}
}
}
Code working OK when load Form. when tbl_FF_Trigger add new value myFlowLayoutPanel1 new UC_Machine
but timer1 not start. I know this because the datagirdview has no data in the newly added UC_Machine.I want when myFlowLayoutPanel1 adds 1 UC_Machine, timer1 will start
Anyone have any advise or solution for this case, please help me. Thanks a lot!
Your question is how to call timer in UC Control in Form Main. The main form is trying to GetInfo from the UC but consider that this might be "backwards" and that the UC Control should be notifying Form Main when it gets the new info instead. Here's what I mean:
Your UC has its own timer1 (we'll get timer1 started don't worry). What main form needs is to be notified when a new query is available in one of the UCs. Giving main form its own timer will interfere with an otherwise-orderly process. Consider making an event in your UC as shown and fire it whenever UC is done getting a new query.
UserControlMachine
Example: UC starts its own timer1 and fires RecordsChanged event when new query completes.
public partial class UserControlMachine : UserControl
{
public UserControlMachine()=>InitializeComponent();
public BindingList<Record> Records { get; } = new BindingList<Record>();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
timer1 = new Timer { Interval = 2500 };
timer1.Tick += onTimer1Tick;
timer1.Start();
dataGridView1.DataSource = Records;
Records.Add(new Record()); // <- Auto-generate columns
dataGridView1.Columns[nameof(Record.DefectName)].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
private System.Windows.Forms.Timer timer1;
private void onTimer1Tick(object sender, EventArgs e) => queryDB();
private void queryDB()
{
// S I M U L A T E D Q U E R Y R E S U L T
Records.Clear();
for (int i = 0; i < Rando4Test.Next(1,5); i++)
{
Records.Add(new Record
{
CRDName = $"CRD-{(char)Rando4Test.Next(65,70)}{Rando4Test.Next(100, 200)}"
});
}
// Notify the Main Form that something has changed.
RecordsChanged?.Invoke(this, EventArgs.Empty);
}
public event EventHandler RecordsChanged;
// For testing purposes
public static Random Rando4Test { get; } = new Random();
}
Main Form
All the main form has to do is listen for RecordsChanged events.
public partial class Form1 : Form
{
public Form1() => InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Simulation: Add 2 machines
for (int i = 0; i < 2; i++)
{
var machine = new UserControlMachine
{
Size = new Size(myFlowLayoutPanel1.Width - SystemInformation.VerticalScrollBarWidth, 200),
BorderStyle = BorderStyle.FixedSingle,
};
myFlowLayoutPanel1.Controls.Add(machine);
// Listen for new query results
machine.RecordsChanged += onAnyUCRecordsChanged;
}
}
private void onAnyUCRecordsChanged(object sender, EventArgs e)
{
int totalDefects = 0;
foreach (var machine in myFlowLayoutPanel1.Controls.OfType<UserControlMachine>())
{
totalDefects += machine.Records.Count;
}
Text = $"Main Form - Total Defects: {totalDefects}";
}
}
WHERE Record class represents a DataGridViewRow
public class Record
{
public string PartNumber { get; set; } =
Guid.NewGuid().ToString().Substring(0, 13).ToUpper();
public string CRDName { get; set; }
public string DefectName { get; set; } = "Unknown Error";
}
I'm quite new to ASP.NET and I need your help.
I'm programming on an application which should help to fix frequent issues. Users can click the displayed cases if it describes their problem. The application searches for more cases or displays a possible solution.
Now what I need for this is some code which creates the buttons dynamically. I googled some ideas and created some code, however I was not able to get it to work.
It works to create the first selection of buttons with the Default_Load method. Also the OnClick event (ButtonClick_System) works fine which means I get the next selection.
From here it starts messing around. The dynamic buttons created in ButtonClick_System don't have a working OnClick action.
Instead of proceeding with ButtonClick_Question (because of btn_system.Command += ButtonClick_Question; in ButtonClick_System) it seems like it just loads the homepage (maybe something wrong with Page_Load?).
The application should do ButtonClick_Question until no more datasets available in database.
I got the following code:
using System;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using Oracle.DataAccess.Client;
namespace Application
{
public partial class _default : System.Web.UI.Page
{
// Variables
private string app_name = "Application";
// ----- Page_Load ----- //
protected void Page_Load(object sender, EventArgs e)
{
Default_Load();
Session["Application"] = app_name;
}
// ----- Methods ----- //
// Load homepage
public void Default_Load()
{
pnl_default.Visible = true;
pnl_content.Visible = false;
HtmlGenericControl html_default = new HtmlGenericControl();
html_default.TagName = "div";
string cmdString = "(...)";
DataTable dtSystems = OraQueryData(cmdString);
foreach (DataRow dtRow in dtSystems.Rows)
{
int system_id = Convert.ToInt32(dtRow["SYSTEM_ID"]);
string system_name = Convert.ToString(dtRow["SYSTEM_NAME"]);
var btn_system = new Button
{
ID = "btn_" + system_name,
Text = system_name,
CssClass = "sys_buttons"
};
btn_system.Command += ButtonClick_System;
btn_system.CommandArgument = Convert.ToString(system_id);
html_default.Controls.Add(btn_system);
}
plh_default.Controls.Clear();
plh_default.Controls.Add(html_default);
}
// Button OnClick Events
protected void ButtonClick_System(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_questions = new HtmlGenericControl();
html_questions.TagName = "div";
int system_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = Convert.ToString(system_id);
html_questions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_questions);
}
protected void ButtonClick_Question(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_ChildQuestions = new HtmlGenericControl();
html_ChildQuestions.TagName = "div";
int parent_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtChildQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtChildQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = question_id;
html_ChildQuestions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_ChildQuestions);
}
// ----- Oracle Data Query Methods ----- //
// Create and execute query on database
public static DataTable OraQueryData(string cmdString)
{
string conString = ConfigurationManager.AppSettings["Connection"];
OracleConnection oraCon = new OracleConnection(conString);
OracleCommand oraCmd = new OracleCommand(cmdString, oraCon);
OracleDataAdapter oraDtAd = new OracleDataAdapter(oraCmd.CommandText, oraCon);
DataTable dt = new DataTable();
oraCon.Open();
oraDtAd.Fill(dt);
oraCon.Close();
return dt;
}
}
}
If I've understood the issue correctly I think you're using the wrong controls for the wrong usages.
What I'd suggest you need to do is bind the collection of FAQ records to a repeater or some other data set display control. You can then have an event on the repeater which can handle which record ID has been clicked, post back with that value and refresh the collection of data from that (maybe in another repeater). Don't dynamically create buttons and bind events to them otherwise you will end up in a mess.
Hope this helps.
I am attempting to access user enter data in dynamic controls in asp.net.
I am not creating the controls in page_load because they exist based on a sql query that is only resolved after the user selects a value from a drop down list.
I have the ids generated so they are consistent and a submit button which refreshes, also I am using ajax update panels. What I am lacking is any code for actually saving the state of the dynamic controls before postback and naturally by the page load point they do not exist yet.
What do I need to do to make sure the controls values carry over?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadDD1();
}
}
private void loadDD1()
{
try
{
ListItemCollection lic = DataAccessHelper.stNumsForName(ddaddressname.SelectedValue.ToString());
ddaddressnumber.DataSource = lic;
ddaddressnumber.DataTextField = "Text";
ddaddressnumber.DataValueField = "Value";
ddaddressnumber.DataBind();
if (tbaddaddressnumber.Text != "")
{
ddaddressnumber.SelectedValue = tbaddaddressnumber.Text;
tbaddaddressnumber.Text = null;
}
}
catch (Exception es)
{
}
}
protected void btret_Click(object sender, EventArgs e)
{
loadAll(); // Once a value from dropdown is selected
}
private void loadAll()
{
int FDDkey = int.Parse(ddaddressnumber.Items[ddaddressnumber.SelectedIndex].Value);
BusinessObjects.ResidenceFDD res = new BusinessObjects.ResidenceFDD();
try
{
AnnArborFDDModel.AnnArborFDDEntities1 com = new AnnArborFDDModel.AnnArborFDDEntities1();
// Communication com = new Communication();
var query = from a in com.Communications
where a.fddkey == res.FDDKey
select a;
var querydd = (from b in com.Communications
where !String.IsNullOrEmpty(b.subject)
select b.subject).Distinct();
var collectiondetails = new List<object>();
// collectiondetails.Add(querydd);
TextBox notestbbase = new TextBox();
DropDownList notesddbase = new DropDownList();
TextBox notestbcomments = new TextBox();
TableRow tr01 = new TableRow();
tr01.Cells.Add(new TableCell());
tr01.Cells.Add(new TableCell());
tr01.Cells[0].Text = "Date:";
tr01.Cells[1].Text = "Correspondent:";
this.tblnotes.Rows.Add(tr01);
TableRow tr02 = new TableRow(); // Not sure if new row needs to be instantiated or not.
tr02.Cells.Add(new TableCell());
tr02.Cells.Add(new TableCell());
notestbbase.ID = "notestbbase";
tr02.Cells[0].Controls.Add(notestbbase);
notesddbase.ID = "notesddbase";
notesddbase.DataSource = querydd.ToList();
notesddbase.DataBind();
notesddbase.Items.Insert(0, emptyItem);
notesddbase.SelectedIndex = 0;
tr02.Cells[1].Controls.Add(notesddbase);
this.tblnotes.Rows.Add(tr02);
TableRow tr03 = new TableRow(); // Not sure if new row needs to be instantiated or not.
tr03.Cells.Add(new TableCell());
notestbcomments = new TextBox();
notestbcomments.ID = "notestbcomments";
notestbcomments.Width = 150;
notestbcomments.Height = 150;
notestbcomments.Wrap = true;
notestbcomments.TextMode = TextBoxMode.MultiLine;
tr03.Cells[0].Controls.Add(notestbcomments);
this.tblnotes.Rows.Add(tr03);
}
catch (Exception ex)
{}
}
protected void btupdate_Click(object sender, EventArgs e)
{
try
{
Dictionary<string, string> idAndValueDictionary = new Dictionary<string, string>();
TextBox tbdatetoadd = (TextBox)FindControl("notestbbase"); //Communications table
DropDownList ddcorrespondanttoadd = (DropDownList)FindControl("notesddbase"); // Communications table
TextBox tbnotestoadd = (TextBox)FindControl("notestbcomments");
}
// There is a catch statement here I am trying not to spam with too much code.
}
Try this, I have not tested this...
Dictionary<string, string> idAndValueDictionary = new Dictionary<string, string>();
Fill the dictionary and when you save the data to viewstate.
idAndValueDictonary.Add(control id, value); // in a loop
ViewState["idAndValueDictionary"] = idAndValueDictionary;
and on postback:
idAndValueDictionary = ViewState["idAndValueDictionary"] as Dictionary<string, string>;
Then loop through, setting the values based on the id's accordingly.
So I am displaying data from an access DB based on which point image is clicked. I have come up with two different ways to do this and I am curious which would be more efficient.
Here are the two different ways I am currently doing this. If you can recommend a better solution I would love to hear about it.
Solution 1 using datagridview which is binded to the access db.
private void risk1_Click(object sender, EventArgs e)
{
pointid.Text = "7";
int numval = Convert.ToInt32(pointid.Text);
//To get the correct row
int id = numval - 1;
//Point Id of the clicked point
textBox1.Text = id.ToString();
pointlbl.Text = dataGridView1.Rows[id].Cells[2].Value.ToString();
//Cat ID of the clicked point
catId.Text = dataGridView1.Rows[id].Cells[5].Value.ToString();
webBrowser1.DocumentText = dataGridView1.Rows[id].Cells[4].Value.ToString();
webBrowser1.Document.ExecCommand("SelectAll", false, null);
webBrowser1.Document.ExecCommand("Copy", false, null);
using (RichTextBox box = new RichTextBox())
{
box.Paste();
box.Rtf = box.Rtf.Replace("<>", "");
this.htmlRichTextBox1.Rtf = box.Rtf;
}
pointPanel.Visible = true;
homePanel.Visible = false;
}
Solution 2 using a select statement
private void risk2_Click(object sender, EventArgs e)
{
pointid.Text = "2";
int numval = Convert.ToInt32(pointid.Text);
//Setup Connection to access db
string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Adam\\Desktop\\braithwaite.mdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
//{
//open connection
conGet.Open();
//String correctAnswer;
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT * FROM Points WHERE point_id = "+numval+"";
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
pointlbl.Text = reader["point"].ToString();
webBrowser1.DocumentText = reader["Description"].ToString();
conGet.Close();
pointPanel.Visible = true;
homePanel.Visible = false;
}
how I save dynamically created Labels and Checkboxes values into sql server
protected void EventDuration_DDL_SelectedIndexChanged(object sender, EventArgs e)
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
Label NewLabel = new Label();
NewLabel.ID = "Label" + i;
var eventDate = Calendar1.SelectedDate.Date.AddDays(i);
NewLabel.Text = eventDate.ToLongDateString();
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
this.Labeldiv.Controls.Add(new LiteralControl("<span class='h1size'>"));
this.Labeldiv.Controls.Add(NewLabel);
this.Labeldiv.Controls.Add(new LiteralControl("</span>"));
this.Labeldiv.Controls.Add(new LiteralControl("<div class='make-switch pull-right' data-on='info'>"));
this.Labeldiv.Controls.Add(newcheck);
this.Labeldiv.Controls.Add(new LiteralControl("</div>"));
this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into Event(EventName,StartDate,EventDuration,StartTime,EndTime,SlotDuration) output inserted.EventId values(#EventName,#StartDate,#EventDuration,#StartTime,#EndTime,#SlotDuration)", con);
cmd1.Parameters.AddWithValue("#EventName", EventName_TB.Text);
cmd1.Parameters.AddWithValue("#StartDate", StartDate_TB.Text);
cmd1.Parameters.AddWithValue("#EventDuration", EventDuration_DDL.Text);
cmd1.Parameters.AddWithValue("#StartTime", StartTime_DDL.Text);
cmd1.Parameters.AddWithValue("#EndTime", EndTime_DDL.Text);
cmd1.Parameters.AddWithValue("#SlotDuration", SlotDuration_DDL.Text);
Int32 id = (Int32)cmd1.ExecuteScalar();
var label = Labeldiv.FindControl("Label1") as Label;
var checkbox = Labeldiv.FindControl("CheckBox1") as CheckBox;
using (SqlCommand cmd2 = new SqlCommand("insert into EventDays(EventDay,EventStatus)values(#EventDay,#EventStatus)", con))
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
var paramDay = cmd2.Parameters.Add("#EventDay", SqlDbType.DateTime);
var paramStatus = cmd2.Parameters.Add("#EventStatus", SqlDbType.Int);
paramDay.Value = label.Text;
paramStatus.Value = checkbox.Checked ? 1 : 0;
cmd2.ExecuteNonQuery();
}
}
con.Close();
}
I have created Labels and CheckBoxes dynamically in EventDuration_DDL_SelectedIndexChanged.
now I want to save these values into sql server in Wizard1_FinishButtonClick.
how I save dynamically created Labels and Checkboxes values into sql server
.
.
.
.
..
You have to recreate those dynamically created labels and check boxes for the button click as well, because when the user clicks the finish button, that causes a post back to the server and the page is recreated, but the dynamic label and check box logic is not executed, thus your database saving logic cannot "find" these controls.
I recommend moving your dynamic label and check box creation logic to a separate method that can be called by the EventDuration_DDL_SelectedIndexChanged() and Wizard1_FinishButtonClick(), like this:
private void BuildDynamicControls()
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
Label NewLabel = new Label();
NewLabel.ID = "Label" + i;
var eventDate = Calendar1.SelectedDate.Date.AddDays(i);
NewLabel.Text = eventDate.ToLongDateString();
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
this.Labeldiv.Controls.Add(new LiteralControl("<span class='h1size'>"));
this.Labeldiv.Controls.Add(NewLabel);
this.Labeldiv.Controls.Add(new LiteralControl("</span>"));
this.Labeldiv.Controls.Add(new LiteralControl("<div class='make-switch pull-right' data-on='info'>"));
this.Labeldiv.Controls.Add(newcheck);
this.Labeldiv.Controls.Add(new LiteralControl("</div>"));
this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
}
}
Now in your event handlers, you can call this method, like this:
protected void EventDuration_DDL_SelectedIndexChanged(object sender, EventArgs e)
{
BuildDynamicControls();
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
BuildDynamicControls();
}
Alternatively, you can call BuildDynamicControls() in the Page_Load. This takes care of other buttons on the page destroying the values when they cause a post back, like this:
protected void Page_Load(object sender, EventArgs e)
{
// Do other page load logic here
BuildDynamicControls();
}
Note: If you go this route, then you will not need to call BuildDynamicControls() in the EventDuration_DDL_SelectedIndexChanged() or Wizard1_FinishButtonClick() methods, because the Page_Load happens before either of those events in the page life-cycle.