I have flow layout panel with SQL and I know how to load items from SQL to flow layout panel as Buttons, but now I need your help every button have click event So how can I control on event of every Button that I load it
items_Panles.Controls.Clear();
SqlConnection con = new SqlConnection("Data Source=DESKTOP-6HNIPQ5;Initial Catalog=Anass;Persist Security Info=True;User ID=sa;Password=123");
SqlDataAdapter sda = new SqlDataAdapter("select * from Table_Employee", con);
DataTable dt = new DataTable();
sda.Fill(dt);
for(int i=0;i<dt.Rows.Count;i++)
{
Button btn = new Button();
btn.Name = "btn" + dt.Rows[i][0].ToString();
btn.Text = dt.Rows[i][1].ToString();
btn.Height = 80;
btn.Width = 75;
items_Panles.Controls.Add(btn);
}
this code is fire when I click on the Individual button
Stub out your click method, for example:
void btn_Click(object sender, EventArgs e) {
Button b = sender as Button;
if (b != null) {
MessageBox.Show(b.Name);
}
}
then when you create the button, attach the handler:
Button btn = new Button();
btn.Click += btn_Click;
Related
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString.Count > 0)
{
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("select * from personalization where ponumber = '" + Request.QueryString["PO"] + "'", VisualConnect);
adapter.Fill(dt);
if (dt.Rows.Count > 0)
{
for (Int32 i = 0; i < dt.Rows.Count; i++)
{
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
HtmlGenericControl td1 = new HtmlGenericControl("td");
Label lbcustomename = new Label();
lbcustomename.ID = "lbline1";
lbcustomename.Text = "Recipient Name: ";
td.Controls.Add(lbcustomename);
tr.Controls.Add(td);
TextBox txtcustombox = new TextBox();
txtcustombox.ID = "txtline1";
txtcustombox.Text = dt.Rows[i]["line1"].ToString();
td1.Controls.Add(txtcustombox);
tr.Controls.Add(td1);
placeholder.Controls.Add(tr);
//Add button after last record
if (i == dt.Rows.Count - 1)
{
tr = new HtmlGenericControl("tr");
td = new HtmlGenericControl("td");
Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Click += btnSubmit_Click;
btnSubmit.Text = "Submit";
btnSubmit.Attributes.Add("runat", "server");
td.Controls.Add(btnSubmit);
td.Attributes.Add("Colspan", "2");
td.Attributes.Add("style", "text-align:center;");
tr.Controls.Add(td);
placeholder.Controls.Add(tr);
}
}
}
}
}
private void btnSubmit_Click(object sender, EventArgs e)
{
// do something
}
}
I have added this code to dynamically draw up fields from a database for input where the user would click the Submit button when completed. However, whenever I click the submit button, it wants to reload the page and the btnSubmit_Click event is never invoked instead. Am I missing something?
i am generating buttons dynamically on page load and on button click event i calling LoadSubClause event which is working fine and with in this event i am creating new buttons. These newly created buttons have LoadDescription event assigned on button click but once i click on any of these buttons it clears the SubClause created buttons and nothing shows up from LoadDescription event.
public void LoadSubClause(object sender, EventArgs e)
{
Button btn = sender as Button;
string ClauseName = btn.Text.ToString();
int counter = 100;
string query = "select SubClause from Output_DocumentContent where Clause ='" + ClauseName.ToString() + "'";
Response.Write(query);
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Legal;Integrated Security=true");
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
Button newButton = new Button();
newButton.Attributes["class"] = "buttonVertical";
newButton.Text = sdr[0].ToString();
newButton.ID = "SubClause"+counter.ToString();
newButton.Click += new EventHandler(LoadDescription);
//buttons.Add(newButton);
PanelSubClause.Controls.Add(newButton);
counter++;
}
con.Close();
}
public void LoadDescription(object sender, EventArgs e)
{
Response.Write("Load Description Event");
}
I need to use a single event handler for multiple buttons. I generated those buttons via while loop according to the database query. I created a single method
void MyButtonClick(object sender, EventArgs e)
{
}
I'm new to the C#. How can I bind all button's events to a single handler.
Code for generating the buttons:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
MydbConnection db = new MydbConnection();
MySqlConnection con = db.connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "select * from categories where online = 1";
cmd.Connection = con;
MySqlDataReader rd;
con.Open();
rd = cmd.ExecuteReader();
int i = 1;
while (rd.Read())
{
Button btn = new Button();
btn.Name = "btn-" + i.ToString();
btn.Tag = i;
btn.Text = rd.GetString(2).ToString();
btn.Height = 60;
btn.Width = 100;
btn.Location = new Point(900, 60 * i + 10);
this.Controls.Add(btn);
i++;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Welcome to SO. You can add this right before this.Controls.Add(btn);
btn.Click += MyButtonClick;
You need to set all of their CLICK properties to the same event handler:
btn.Click += new EventHandler(MyButtonClick);
That should make it so that anytime you click any of the buttons, MyButtonClick() is the event that triggers. Of course, if you need to figure out WHICH button was clicked, then you need to check the sender parameter within the event, where 'i' is one of the number values you assigned to a button in the loop:
(if sender == btn-i) then ....
I'm trying to convert a WinForms project to an ASP.Net project. Currently I'm struggling with a basic problem. I need to create a Button dynamically an display it on the page after the user selected a row in a GridView. Before I add the Button to the page I set an Click event handler. The problem is, that this event handler is never fired. I've tried to create the Button dynamically when the SelectedIndexChanged event of the GridView is fired and to create the Button as an instance member and set the event handler in the OnInit method of the class. Neither worked. Here is my code for the first attempt:
protected void dgvReports_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.dgvReports.SelectedIndex >= 0)
{
Report rpt = (Report)bs.Current;
Control parameterCaption = this.divParameters.Controls[0];
Button btnAccept = new Button() { Text = "Get results" };
bool newLine = false;
this.divDescription.Visible = true;
this.divParameters.Visible = true;
this.divParameters.Controls.Clear();
this.divParameters.Controls.Add(parameterCaption);
this.txtDescription.Text = rpt.Description;
btnAccept.Click += new EventHandler(btnAccept_Click);
foreach (ReportParameter parameter in rpt.Parameters)
{
if (parameter.Visible)
{
this.divParameters.Controls.Add(new Label() { Text = parameter.Description, Width = 150, CssClass = "parameter" });
this.divParameters.Controls.Add(new TextBox() { Text = parameter.DefaultValue, Width = 300, ID = parameter.Name });
if (newLine)
{
this.divParameters.Controls.Add(new LiteralControl("<br />"));
}
newLine = !newLine;
}
}
this.divParameters.Controls.Add(new LiteralControl("<br /> <div style='text-align:center'>"));
this.divParameters.Controls.Add(btnAccept);
this.divParameters.Controls.Add(new LiteralControl("</div>"));
}
}
void btnAccept_Click(object sender, EventArgs e)
{
Report rpt = (Report)bs.Current;
SqlConnection con = new SqlConnection(global::System.Configuration.ConfigurationManager.ConnectionStrings["DP2ConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand();
DataTable dataTable = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(com);
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = rpt.DbProcedure;
dataTable.Locale = CultureInfo.CurrentCulture;
foreach (Control control in this.divParameters.Controls)
{
if (control is TextBox)
{
TextBox txt = control as TextBox;
com.Parameters.AddWithValue(txt.ID, txt.Text);
}
}
foreach (ReportParameter parameter in rpt.Parameters)
{
if (!parameter.Visible)
{
com.Parameters.AddWithValue(parameter.Name, parameter.DefaultValue);
}
}
sda.Fill(dataTable);
}
Dynamic controls in asp.net are never easy. Your event handler is probably not being included in the View State and therefore not persisting on postbacks, like when they click the button in question. The button has to be remade on each page load, which event handler being attached then as well- if possible, I'd save yourself a headache and try showing and hiding the button.
Try changing btnAccept.Click += new EventHandler(btnAccept_Click); to btnAccept.Click += new RoutedEventHandler(btnAccept_Click);
I am creating the dynamic text boxes and buttons but when I add values it does not save any thing with I enter into the data base. Well it does not give any error when I enter the values. please tell me if I am doing any thing wrong.
protected void Page_Load(object sender, EventArgs e)
{
Session["clicks"] = "";
}
protected void btnCU_Click(object sender, EventArgs e)
{
Button Ad_AB = new Button();
Ad_AB.ID = "btnAd_add";
Ad_AB.Text = "Add";
Ad_AB.Click += new EventHandler(Ad_AB_Click);
TextBox txtAd_AUN = new TextBox();
TextBox txtAd_AP = new TextBox();
txtAd_AUN.ID = "txtAd_AUN".ToString() ;
txtAd_AP.ID = "txtAd_AP".ToString() ;
Label lblAd_AEUN = new Label();
Label lblAd_AEP = new Label();
lblAd_AEUN.Text = "Enter User Name :";
lblAd_AEP.Text = "Enter Passowrd :";
pnlCNU.Controls.Add(Ad_AB);
pnlCNU.Controls.Add(lblAd_AEUN);
pnlCNU.Controls.Add(txtAd_AUN);
pnlCNU.Controls.Add(lblAd_AEP);
pnlCNU.Controls.Add(txtAd_AP);
if(Session["clicks"].ToString() == "G"){
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Omer\\Documents\\Visual Studio 2010\\WebSites\\WAPPassignment\\App_Data\\LoginStuff.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
SqlDataReader dr;
con.Open();
cmd = new SqlCommand("Insert into WhatTypes(UserName, Password) Values ('" + txtAd_AUN.Text + "', '" + txtAd_AP.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
void Ad_AB_Click(object sender, EventArgs e)
{
//throw new NotImplementedException();
Session["clicks"] = "G";
}
Unless the dynamically added controls are added at the init or preinit stage, they will not persist beyond a postback. Controls added after this need to be recreated on each post back.
But in your case, I would suggest that you just create the controls at design time inside a div or panel with its Visible property set to false and then when the button is clicked, just change the Visible property to true. It looks like you just want to show some login boxes when the button is clicked.