C# dynamically generate button for single event handler - c#

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 ....

Related

Dynamically create button click event not working

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");
}

Error going to next form on clicking datagride tuple

My code-
public void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
Form2 f2 = new Form2(id);
f2.textBox1.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
f2.textBox2.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
f2.textBox3.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
f2.textBox4.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
f2.Show();
this.Hide();
}
public void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
Form2 f2 = new Form2(id);
f2.textBox1.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
f2.textBox2.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
f2.textBox3.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
f2.textBox4.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
f2.Show();
this.Hide();
}
my gui-
My problem is that when I click on the datagrid tuple it is not going to the next form.
It is just freezing.
edit-
this how I am filling the datagrid -
CheckBox[] Locations = { checkBox1, checkBox2, checkBox3 };
CheckBox[] Profiles = { checkBox4, checkBox5, checkBox6 };
string locs = string.Join(" or ", Locations.Where(c => c.Checked).Select(x => $"location = '{x.Text}'"));
string profs = string.Join(" or ", Profiles.Where(c => c.Checked).Select(x => $"profile = '{x.Text}'"));
MessageBox.Show(locs);
string query = $"select * from jobs where ({locs}) and profile in(select profile from jobs where ({profs}))";
OracleCommand comm2 = new OracleCommand(query, conn);
OracleDataAdapter MyAdapter = new OracleDataAdapter();//adapter acts as interface btw database and dataset(which is collectio of tables)
MyAdapter.SelectCommand = comm2;
DataTable dTable = new DataTable();//datatable represents a single table in database
MyAdapter.Fill(dTable);
dataGridView1.DataSource = dTable;
this might help in debugging.So my query basically returns a row of tuples and I will click any of the rows and it should go to another form where the column values of that row are stored in the textbox of the second form.
If you take a closer look at CellContentClick event, you'll see that this event:
Occurs when the content within a cell is clicked.
I just tried your posted code, and it works. It's a bit tricky though using CellContentClick event because you cursor has to click on the content of the cell exactly. I advise you to use CellClick event instead.
This event:
Occurs when any part of a cell is clicked.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Form2 f2 = new Form2(id);
f2.textBox1.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
f2.textBox2.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
f2.textBox3.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
f2.textBox4.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
f2.Show();
this.Hide();
}
Update:
Since you're telling me that by adding this code, it also didn't work. You need to make sure that your DataGridView has been subscribed to those events:
Open you form in design view.
Click on your DataGridView
Press F4.
Now check the events. They should contain the name of the function you added. Like this:
If you prefer to do this programatically, you can add this code in the Form.Load event:
dataGridView1.CellClick += dataGridView1_CellClick;

flow layout panel

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;

Event handler for dynamically created Button

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);

Dynamically created TextBoxes not saving values

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.

Categories