I am using the following lines of code for a button in C# :
void reserve_click(object sender, EventArgs e)
{
string req = ((Button)sender).ID;
}
protected void Button2_Click(object sender, EventArgs e)
{
issuedBooks.Visible = false;
search.Visible = true;
string text = TextBox1.Text;
string selectCommand = "SELECT id, title, author FROM book WHERE title LIKE '%" + text + "%' OR author LIKE '%" + text + "%'";
string conString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlDataAdapter dad = new SqlDataAdapter(selectCommand, conString);
DataTable dtblCategories = new DataTable();
dad.Fill(dtblCategories);
DataView view = new DataView(dtblCategories);
foreach (DataRowView row in view)
{
TableRow newrow = new TableRow();
TableCell newcell1 = new TableCell();
TableCell newcell2 = new TableCell();
TableCell newcell3 = new TableCell();
newcell1.Text = row["title"].ToString();
newrow.Cells.Add(newcell1);
newcell2.Text = row["author"].ToString();
newrow.Cells.Add(newcell2);
string book_id = row["id"].ToString();
Button btn = new Button();
btn.ID = "Button_1" + book_id;
btn.Text = "Reserve";
btn.Click += new EventHandler(reserve_click);
newcell3.Controls.Add(btn);
newrow.Cells.Add(newcell3);
search.Rows.Add(newrow);
}
I am using the above code in a dynamically added button in a table cell. But the above EventHandler is not working or getting fired. I am using asp.net and C#for the first time. Can someone help me out ? Thanks.
here is the answer.Try it
Page_Load()
{
Button b = new Button();
b.ID = topic.Topic_Id + "_1"; // topic_Id is my unique ID for each topic on the blog
b.Text = "Edit";
b.ToolTip = "Edit";
b.CommandArgument = b.ID; //passing this to event handler
b.Command += new CommandEventHandler(b_Command); //handler
}
void b_Command(object sender, CommandEventArgs e)
{
System.Windows.Forms.MessageBox.Show(e.CommandArgument.ToString());
}
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 working on a website that will act as a blog. My issue is with the comments section and it deals with the alignment of child comment panels. I try to add CSS to float the panels right, but they stay on the left. I have also tried setting the HorizontalAlign of the parent panels to right.
For more context, this is an image of the comments section:
As you can see, the child comments panels are sticking to the left.
This is the method where I am dynamically creating the comments section into an exiting panel called Panel1.
protected void drawComments(string ID, int NumTabs, Panel parentPanel) {
string hash = ID;
SqlConnection conn = new SqlConnection(Secret Stuff);
string cmdStr = "SELECT * FROM Comments WHERE ParentID=#searchHash";
SqlCommand cmd = new SqlCommand(cmdStr, conn);
cmd.Parameters.Add("#searchHash", SqlDbType.NVarChar).Value = hash;
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
Panel tempPanel;
if (reader.HasRows)
{
while (reader.Read())
{
ID = reader.GetString(4);
tempPanel = new Panel();
tempPanel.BorderStyle = BorderStyle.Solid;
tempPanel.BorderColor = System.Drawing.ColorTranslator.FromHtml("#2461bf");
tempPanel.Width = new Unit((100 - (NumTabs * 5)).ToString() + "%");
tempPanel.Attributes.Add("style", "margin-left:auto;");
tempPanel.Attributes.Add("style", "margin-right:auto;");
if (NumTabs > 0)
{
tempPanel.Attributes.Add("style", "margin-bottom:5px");
// tempPanel.Attributes.Add("style", "border-top-style:none");
tempPanel.Attributes.Add("style", "border-left-style:none");
// tempPanel.Attributes.Add("style", "border-right-style:solid");
tempPanel.Attributes.Add("style", "border-bottom-style:none");
}
else
{
tempPanel.Attributes.Add("style", "margin-top:50px");
// Panel1.Controls.Add(new LiteralControl("<BR />"));
}
Label currComment = new Label();
Label currAuthor = new Label();
currComment.Text = reader.GetString(0);
currAuthor.Text = reader.GetString(3).Split('#')[0];
Table tbl = new Table();
tbl.Width = new Unit("100%");
tbl.Attributes.Add("style", "margin-left:auto");
tbl.Attributes.Add("style", "margin-right:auto");
TableRow tblrow1 = new TableRow();
TableCell tblcell11 = new TableCell();
TableCell tblcell12 = new TableCell();
tblcell11.HorizontalAlign = HorizontalAlign.Right;
tblcell11.Width = new Unit("30%");
tblcell11.Text = currAuthor.Text + " Says:";
tblcell12.HorizontalAlign = HorizontalAlign.Left;
tblcell12.Text = currComment.Text;
tblcell12.Width = new Unit("70%");
tblrow1.Cells.Add(tblcell11);
tblrow1.Cells.Add(tblcell12);
tbl.Rows.Add(tblrow1);
TableCell tblcell21 = new TableCell();
tblcell21.Width = new Unit("30%");
ImageButton replyButton = new ImageButton();
replyButton.ImageUrl = "~/images/replybutton.png";
replyButton.Attributes.Add("style", "float:right");
replyButton.Width = 77;
replyButton.ID = ID;
replyButton.Command += addReply;
ImageButton likeButton = new ImageButton();
likeButton.ImageUrl = "~/images/likebutton.png";
likeButton.Attributes.Add("style", "float:right");
likeButton.Width = 65;
Label likeCount = new Label();
likeCount.Attributes.Add("style", "float:right");
likeCount.BorderStyle = BorderStyle.Groove;
likeCount.Text = "0";
TableCell tblcell22 = new TableCell();
tblcell22.HorizontalAlign = HorizontalAlign.Left;
tblcell22.Controls.Add(likeCount);
tblcell22.Controls.Add(likeButton);
tblcell22.Controls.Add(replyButton);
tblcell22.Width = new Unit("70%");
TableRow tblrow2 = new TableRow();
tblrow2.Cells.Add(tblcell21);
tblrow2.Cells.Add(tblcell22);
tbl.Rows.Add(tblrow2);
tempPanel.Controls.Add(tbl);
//tempPanel.Controls.Add(currComment);
if (NumTabs>0)
{
parentPanel.Controls.Add(tempPanel);
}
else
Panel1.Controls.Add(tempPanel);
drawComments(reader.GetString(4), NumTabs + 1, tempPanel);
}
}
}
catch (Exception ex)
{
lblDebug.Text = ex.ToString();
}
finally { conn.Close(); }
}
Any suggestions to get these child panels right aligning would be greatly appreciated. I hope you can understand what I am going for through this poorly written code by a 15 year old.
I have a search function which looks up specific users in my OleDb database. For each user, a row in a table is created containing his name, boolean saying if he is an admin or not and a delete button. The delete button is not working as expected, it doesn't execute the method that is linked to it. My code is located in the Search_Click event which executes right after the admin clicks the search button to search for specific users.
I tried to place a pre-defined button from my code but in Page_Load instead and it works as expected. How can I get the button to work from the Search_Click as well?
Basically, after dynamically creating the LinkButtons according to the user search text and clicking the search button (Search_Click) I need to find a way to register the click event on page load event, I do not know how to do that because the linkbuttons HAVE to be created in the click event of the search button but they also have to be registered via page load.
using (OleDbDataReader reader = cmd.ExecuteReader())
{
Table table = new Table();
TableRow row = new TableRow();
TableCell cell = new TableCell();
Label label = new Label();
while (reader.Read())
{
row = new TableRow();
cell = new TableCell();
label = new Label();
label.Text = reader.GetString(0);
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
label = new Label();
label.Text = reader.GetBoolean(1).ToString();
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
LinkButton button = new LinkButton();
button.Text = "Delete";
button.ID = (string) reader["uName"];
button.CommandName = (string)reader["uName"];
button.Click += new EventHandler(DeleteUser);
cell.Controls.Add(button);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
table.Rows.Add(row);
}
table.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto");
table.Style.Add(HtmlTextWriterStyle.MarginRight, "auto");
TableHolder.Controls.Add(table);
}
DeleteUser:
protected void DeleteUser(object sender, EventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
string path = Server.MapPath(#"App_Data/ArcadeDatabase.accdb");
using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Persist Security Info = False;"))
{
try
{
con.Open();
}
catch(Exception ex)
{
helper.Log("OleDbError", ex.Message);
}
if(con.State == System.Data.ConnectionState.Open)
{
using (OleDbCommand cmd = new OleDbCommand("DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';", con))
{
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
helper.Log("OleDbError", ex.Message);
}
}
}
con.Dispose();
}
path = "";
}
catch (Exception ex)
{
helper.Log("Admin", ex.Message);
}
}
The event handler for dynamic controls need to be registered during Page_Load / Page_Init events to be triggered (see this link).
So, You have to add your Delete button and its event handler in page_load or init. to find ID of the control which cause postback in Page_Init event, see this
UPDATE:
OK, i add this code to proof it can be done without problems.
To see how it works: create a new Web Form and paste the following HTML & Code-Behinds into it. Then run the app and type some name in Search TextBox (eg: John or Ali) and press Search Button to filter the results.
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string searchName = "";
if (SearchTextBox.Text != "") //if (this.GetPostBackControlUniqueID() == Search.UniqueID) //Search button is clicked!
{
searchName = SearchTextBox.Text;
}
addTable(searchName);
}
void addTable(string searchName)
{
string[] data = new[] {
"John, false, usrJohn"
,"Alex, false, usrAlex"
,"Ali, true, usrAli"
};
//using (OleDbDataReader reader = cmd.ExecuteReader())
//{
Table table = new Table(); table.CellPadding = 10;
TableRow row;
TableCell cell;
Label label;
foreach(string dataItem in data) //while (reader.Read())
{
string[] reader = dataItem.Split(',');
if (reader[0].IndexOf(searchName, StringComparison.OrdinalIgnoreCase) < 0) continue; //search not found (in real app, you use sql where clause for this, but this is just for test)
row = new TableRow();
cell = new TableCell();
label = new Label();
label.Text = reader[0].Trim(); //reader.GetString(0);
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
label = new Label();
label.Text = reader[1].Trim(); //reader.GetBoolean(1).ToString();
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
LinkButton button = new LinkButton();
button.Text = "Delete";
string uName = reader[2].Trim();
button.ID = uName; //(string)reader["uName"];
button.CommandName = uName; //(string)reader["uName"];
button.Click += new EventHandler(DeleteUser);
cell.Controls.Add(button);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
table.Rows.Add(row);
}
table.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto");
table.Style.Add(HtmlTextWriterStyle.MarginRight, "auto");
TableHolder.Controls.Add(table);
//} //end using OleDbDataReader reader
}
protected void Search_Click(object sender, EventArgs e)
{
//addTable(SearchTextBox.Text); //already done in Page_Load
}
protected void DeleteUser(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
//using (OleDbCommand cmd = new OleDbCommand("DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';", con))
string sql = "DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';";
//execute the sql ... (in real app)
TableHolder.Controls.Add(new LiteralControl("The sql was: " + sql));
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString("HH:mm:ss");
}
} //end class
And this is the helper extension method to Get UniqueID of PostBack Control:
// ***********************************************************************
public static class MyWebPageExtensions
{
public static string GetPostBackControlUniqueID(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
string controlName = page.Request.Params["__EVENTTARGET"]; //this method works only for link buttons which use javascript: __doPostBack(...) and not input type=submit buttons. Note: it is also available in Request.Form collection but this doesn't require to loop over Form.
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// __EVENTTARGET is null, the control is a button (not javascript linkButton), we need to iterate over the form collection to find it
foreach (string id in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property" in their Id which identifies mouse x and y coordinates
if (id.EndsWith(".x") || id.EndsWith(".y"))
{
string id2 = id.Substring(0, id.Length - 2);
control = page.FindControl(id2);
}
else
{
control = page.FindControl(id);
}
if (control is IButtonControl) break;
}
}
return control == null ? String.Empty : control.UniqueID;
}
}
I'm Trying to filter a combo box using its text property in all characters of Items not only Beginning of them. I'm trying below code in TextChanged event of my combo box. but unfortunately combo box resets after entering any key:
private void cmbCompany_TextChanged(object sender, EventArgs e)
{
string QueryCompany = string.Format("select id,title from acc.dl where title LIKE '%" + cmbCompany.Text + "%' union select null , null order by title");
SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
DataTable DT1 = new DataTable();
DA1.Fill(DT1);
cmbCompany.DisplayMember = "Title";
cmbCompany.ValueMember = "id";
cmbCompany.DataSource = DT1;
}
connection string "con" is defined and opened.
thanks for your helps.
Below part of code which works for me where searching part works not only at the begining but also in the middle. I paste also additional part responsible for move focus to the next control on the form after you hit enter button.
Initialization part:
public Form1()
{
InitializeComponent();
cmbItems = new List<ComboBoxItem>();
InitializeComboBox();
}
private void InitializeComboBox()
{
Random rand = new Random();
for (int i = 0; i <= 1500; i++)
{
int counter = rand.Next(1, 105000);
cmbItems.Add(new ComboBoxItem("randomNumber" + counter, "ID_" + counter));
}
comboBox1.DataSource = cmbItems;
}
Filtering part:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
if (comboBox1.Text == string.Empty)
{
comboBox1.DataSource = cmbItems; // cmbItems is a List of ComboBoxItem with some random numbers
comboBox1.SelectedIndex = -1;
}
else
{
string tempStr = comboBox1.Text;
IEnumerable<ComboBoxItem> data = (from m in cmbItems where m.Label.ToLower().Contains(tempStr.ToLower()) select m);
comboBox1.DataSource = null;
comboBox1.Items.Clear();
foreach (var temp in data)
{
comboBox1.Items.Add(temp);
}
comboBox1.DroppedDown = true;
Cursor.Current = Cursors.Default;
comboBox1.SelectedIndex = -1;
comboBox1.Text = tempStr;
comboBox1.Select(comboBox1.Text.Length, 0);
}
}
Moving focus part:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\r') return;
if (this.ActiveControl != null)
{
this.SelectNextControl(this.ActiveControl, true, true, true, true);
}
e.Handled = true; // Mark the event as handled
}
I hope that helps someone.
you can add a textbox to your form and use it's text to filter :
string QueryCompany =
string.Format(
"select id,title from acc.dl where dltype in (2,4) union select null , null order by title");
SqlDataAdapter DA1 = new SqlDataAdapter(QueryCompany, con);
con.Open();
DataTable DT1 = new DataTable();
DA1.Fill(DT1);
con.Close();
DataView dv1 = new DataView(DT1);
dv1.RowFilter = "Title like '%" + txtCompany.Text + "%' or Title is null";
cmbCompany.DisplayMember = "Title";
cmbCompany.ValueMember = "id";
cmbCompany.DataSource = dv1;
and in selected index changed event :
txtCompany.Text = cmbCompany.Text;
for example: I generate two combo-boxes box1 and box2 dynamically(on run time with a add button click) and on the selected index change of box1, items in box2 should be changed ;data in both boxes is fetched from database.
int cnt = 0;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection conb = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.BusinessUltra1_2ConnectionString"].ConnectionString);
public Form2()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
cnt++;
AddNewComboBox();
AddNewComboBox1();
}
private void AddNewComboBox()
{
ComboBox myNewComboBox = new ComboBox();
myNewComboBox.Name = "ComboBox1" + cnt.ToString();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from company", con);
DataSet ds = new DataSet();
adp.Fill(ds, "company");
myNewComboBox.DataSource = ds.Tables["company"];
myNewComboBox.DisplayMember = ds.Tables["company"].Columns[0].ToString();
myNewComboBox.ValueMember = ds.Tables["company"].Columns[0].ToString();
//Program.counteritems = myNewComboBox.SelectedValue.ToString();
myNewComboBox.SelectedIndexChanged += new EventHandler(myNewComboBox_SelectedIndexChanged);
flowLayoutPanel1.Controls.Add(myNewComboBox);
con.Close();
}
private void AddNewComboBox1()
{
//string xyz = Program.counteritems;
ComboBox myNewComboBox1 = new ComboBox();
myNewComboBox1.Name = "ComboBox2" + cnt.ToString();
conb.Open();
SqlDataAdapter adp1 = new SqlDataAdapter("select * from company", con);
DataSet ds1 = new DataSet();
adp1.Fill(ds1, "company");
myNewComboBox1.DataSource = ds1.Tables["company"];
myNewComboBox1.DisplayMember = ds1.Tables["company"].Columns[1].ToString();
myNewComboBox1.ValueMember = ds1.Tables["company"].Columns[1].ToString();
//myNewComboBox_SelectedIndexChanged(sender);
myNewComboBox1.SelectedIndexChanged += new EventHandler(myNewComboBox1_SelectedIndexChanged);
flowLayoutPanel2.Controls.Add(myNewComboBox1);
//changefunction();
conb.Close();
}
void myNewComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var cbox1 = sender as ComboBox;
if (cbox1 != null)
{
if (cbox1.Name == "ComboBox1" + cnt.ToString())
{
var cbox2 = flowLayoutPanel2.Controls.OfType<ComboBox>().Where(c => c.Name == "ComboBox2" + cnt.ToString()).FirstOrDefault();
cbox2.SelectedValue = cbox1.SelectedValue.ToString();
con2.Open();
SqlDataAdapter adfgtyu = new SqlDataAdapter("select * from Cat_Comp_Item where (Category_Name='" + cbox1.SelectedText + "') ", con2);
DataSet dsft = new DataSet();
adfgtyu.Fill(dsft, "Cat_Comp_Item");
cbox2.DataSource = dsft.Tables["Cat_Comp_Item"];
cbox2.DisplayMember = dsft.Tables["Cat_Comp_Item"].Columns[1].ToString();
con2.Close();
}
}
//string combochange1 = ((ComboBox)sender).Text;
//if (!string.IsNullOrEmpty(myNewComboBox.SelectedValue.ToString()))
//{
// myNewComboBox1.SelectedValue = myNewComboBox.SelectedValue.ToString();
//}
}
private void Form2_Load(object sender, EventArgs e)
{
AddNewComboBox();
AddNewComboBox1();
}
void myNewComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Press OK to select this ");
}
I think you should bind first combobox value and second combobox add just text(---select---) on add button and letter on first combobox index change bind second combobox
You can do as below
private void myNewComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var cbox1 = sender as ComboBox;
if (cbox1 != null)
{
if (cbox1.Name == "ComboBox1")
{
var cbox2 = flowLayoutPanel2.Controls.OfType<ComboBox>().Where(c => c.Name == "ComboBox2").FirstOrDefault();
cbox2.SelectedValue = cbox1.SelectedValue.ToString();
}
}
}
To Do that you need to set comboBox2.ValueMember and comboBox1.ValueMember as same column in your company Table. select ID column or primary key column for that.
And also name your comboboxes as ComboBox1 and ComboBox2 when you create it like below
ComboBox myNewComboBox = new ComboBox();
myNewComboBox.Name = "ComboBox1";
And do the same for ComboBox2