I am creating buttons dynamically using a SQL query:
private void createPagingButtons(DateTime firstDayofWeek, DateTime lastDayofWeek)
{
int i = 1;
//get query that holds all of the names for a date range
SqlDataReader returnedQuery = getDefaultUser(firstDayofWeek, lastDayofWeek);
while (returnedQuery.Read())
{
string buttonName = returnedQuery["Person"].ToString();
string[] splitString = buttonName.Split('(');
Button btn = new Button();
btn.ID = buttonName;
btn.Click += new EventHandler(btn_Click);
btn.Text = splitString[0];
btn.Width = Convert.ToInt32(splitString[0].Length)*9;
btn.CssClass = "dynamicButtons";
pagingPanel.Controls.Add(btn);
i++;
}
}
Because of this, I don't have specific names for them that are static on the ASP.NET side. On postback I would like to button.focus() the one that was clicked.
How do I achieve this?
In btn_Click(), set a page-level variable (e.g., this.clickedButtonId) to the ID and then in createPagingButtons() call btn.Focus() if btn.ID==clickedButtonId:
string clickedButtonId;
private void createPagingButtons(DateTime firstDayofWeek, DateTime lastDayofWeek)
{
int i = 1;
SqlDataReader returnedQuery = getDefaultUser(firstDayofWeek, lastDayofWeek);
while (returnedQuery.Read())
{
string buttonName = returnedQuery["Person"].ToString();
Button btn = new Button();
btn.ID = buttonName;
btn.Click += new EventHandler(btn_Click);
//...
pagingPanel.Controls.Add(btn);
if (btn.ID==this.clickedButtonId) btn.Focus();
i++;
}
}
private void btn_Click(object s, EventArgs e)
{
this.clickedButtonId = ((Button) s).ID;
}
Related
I'm looking for a solution to open folders with dynamically created buttons. Since I'm new to coding the solution i found so far is a bit wonky. Because im using a Textbox to get an actual string value which I can use.
public string MainDirPath = #"C:\....";
public string DirPath { get; set; }
public class Person
{
public string Name { get; set; }
}
private void Btn2_Click(object sender, RoutedEventArgs e)
{
Button Btn;
Person pers;
TextBox tb;
StackPanel s;
List<string> lstDirs = new List<string>(Directory.GetDirectories(MainDirPath));
foreach (string Dir in lstDirs)
{
Btn = new Button();
pers = new Person();
tb = new TextBox();
s = new StackPanel();
pers.Name = Dir;
tb.Text = Dir;
Btn.Content = tb;
Btn.Height = 200;
Btn.Name = "Button_" + (++i).ToString();
Btn.Click += new RoutedEventHandler(Btn_Click);
tb.MouseDoubleClick += new MouseButtonEventHandler(Tb_DoubleClick);
s.Children.Add(Btn);
StkPnl_MG.Children.Add(s);
}
}
void Btn_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
}
void Tb_DoubleClick(object sender, RoutedEventArgs e)
{
TextBox tb = sender as TextBox;
DirPath = tb.Text;
lstBox.Items.Add(tb.Text);
}
I was using Google to find a better soulution, but I might not know the right therms to look for.
I'm trying to apply a RowFilter to a DataTable but the problem with the DataTable is, there are non usual ColumnNames given. Like some ending on a point or some others have spaces in them and so on.
As an example consider this code:
public partial class Form1 : Form
{
public Button ClickMe = new Button();
public DataTable TestTable = new DataTable();
public DataGridView TestView = new DataGridView();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Size = new Size(500, 500);
TestView.Size = new Size(300, 300);
ClickMe.Size = new Size(100, 50);
ClickMe.Text = "Click Me!";
ClickMe.Location = new Point(100, 400);
this.Controls.Add(TestView);
this.Controls.Add(ClickMe);
TestView.Visible = true;
TestTable.Columns.Add(new DataColumn("Addressnumb."));
TestTable.Columns.Add(new DataColumn("SecondColumn"));
TestView.DataSource = TestTable;
ClickMe.MouseClick += ClickMe_MouseClick;
for (int i = 0; i < 10; i++)
{
DataRow Row = TestTable.NewRow();
Row["Addressnumb."] = i.ToString();
Row["SecondColumn"] = "Text " + i.ToString();
TestTable.Rows.Add(Row);
}
}
private void ClickMe_MouseClick(object sender, MouseEventArgs e)
{
MessageBox.Show("Filtering for SecondColumn");
TestTable.DefaultView.RowFilter = "SecondColumn LIKE '%1'";
MessageBox.Show("Filtering for Addressnumb.");
TestTable.DefaultView.RowFilter = "Addressnumb. LIKE '%1'";
}
}
Is there a way how one can escape the characters or mask them that a RowFilter still can be applied?
I'm creating dynamically generated buttons, and when I click on the button, the Add_Click method doesn't get fired up.
Here is a sample from my code:
protected void SearchRec(object sender, EventArgs e)
{
SearchResultsPanel.Controls.Clear();
string text_to_search = SearchTB.Text;
Friends RecToSearch = new Friends();
List<Friends> ListNFU = DBS.getNonFriendUsers(User.Identity.Name.ToString(), text_to_search);
if (ListNFU.Count != 0)
{
foreach (Friends NFRIndex in ListNFU)
{
string _FriendsOutput = FR_output(NFRIndex);
HyperLink RecHyperLink = new HyperLink();
RecHyperLink.Text = _FriendsOutput;
RecHyperLink.CssClass = "HyperLinkFriends";
RecHyperLink.ID = NFRIndex.UdName;
SearchResultsPanel.Controls.Add(new LiteralControl("<div style='height:32px'>"));
SearchResultsPanel.Controls.Add(RecHyperLink);
Button addUser = new Button();
addUser.CssClass = "ApproveBTN";
addUser.Text = "send";
addUser.Click += new EventHandler(Add_Click);
addUser.ID = NFRIndex.UdName + "3";
SearchResultsPanel.Controls.Add(addUser);
}
}
else
{
Label NoResultsLabel = new Label();
NoResultsLabel.Text = "Nothing is found";
SearchResultsPanel.Controls.Add(NoResultsLabel);
}
SearchResultsPanel.Controls.Add(new LiteralControl("</div>"));
}
private void Add_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string _tempID = btn.ID;
string id = _tempID.Substring(0, _tempID.LastIndexOf('3'));
DateTime cdate = new DateTime();
cdate = DateTime.Now;
DBS.AddFriend(User.Identity.Name, id, cdate);
btn.Visible = false;
btn.NamingContainer.FindControl(id).Visible = false;
}
Note: I did something very similar on page_load and it does work.
That is because when the page is reloaded, the control is most probably not recreated. That means that the event won't fire indeed.
You need to place this kind of code in the Page_Load so it gets recreated at postback.
I have created 5 text boxes in a button click event and i have to get the values in the text boxes when the dynamically generated button is clicked.
protected void Button1_Click(object sender, EventArgs e)
{
for(int i=0;i<5;i++)
{
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
HtmlGenericControl tdbtn = new HtmlGenericControl("td");
TextBox txt=new TextBox();
txt.ID="txt_"+i.ToString();
td.Controls.Add(txt);
Button btn=new Button();
btn.ID="btn_"+i.ToString();
btn.Click+=new EventHandler(btnpay_Click);
btn.Text="Pay";
tdbtn.Controls.Add(btn);
tr.Controls.Add(td);
tr.Controls.Add(tdbtn);
PlaceHolder1.Controls.Add(tr);
}
}
But i couldn't get the Values in the text boxes at btnpay_Click
protected void btnpay_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn = sender as Button;
string[] splitvaues = btn.ID.Split('_');
string identity = splitvaues[1];
TextBox txt = new TextBox();
txt =PlaceHolder1.FindControl("txt_" + identity) as TextBox;
}
Can Anybody tell me a way to solve this problem?
Your problem is that FindControl doesn't recurse down the control tree. It only searches the controls directly in the ControlCollection of the container.
This method will find a control only if the control is directly
contained by the specified container; that is, the method does not
search throughout a hierarchy of controls within controls.
You need to write a recursive FindControl. Something like:
public static Control FindControlRecursive(this Control control, string id)
{
if (control == null || control.ID == id) return control;
foreach (var c in control.Controls)
{
var found = c.FindControlRecursive(id);
if (found != null) return found;
}
return null;
}
try this code.....
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
createcontrol();
}
}
private void createcontrol()
{
for (int i = 0; i < 5; i++)
{
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
HtmlGenericControl tdbtn = new HtmlGenericControl("td");
TextBox txt = new TextBox();
txt.ID = "txt_" + i.ToString();
td.Controls.Add(txt);
Button btn = new Button();
btn.ID = "btn_" + i.ToString();
btn.Click += new EventHandler(btnpay_Click);
btn.Text = "Pay";
tdbtn.Controls.Add(btn);
tr.Controls.Add(td);
tr.Controls.Add(tdbtn);
plh1.Controls.Add(tr);
}
}
protected void btnpay_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn = sender as Button;
string[] splitvaues = btn.ID.Split('_');
string identity = splitvaues[1].ToString();
TextBox txt = new TextBox();
txt = plh1.FindControl("txt_" + identity) as TextBox;
string q = txt.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
createcontrol();
}
I have a webpart that is quire simple. CLick on "Add" link that sets a 2 text boxes visible. Type in some text and click "Save" button but the click event won't fire. I'm pasting the code it hopes of some suggestion. I've searched for solutions but haven't found anything I can go on. I realize what maight be the issue but don't know how to corrct it. I need to be able to wireup and event with the handler sotimes before the page renders and I tried to override the OnPreRender method but it did not work in right moment.
Other minor issue that I will need to address is that the onFocus method doesn't work in txtMyLinkName.Focus(). Thanks for your help! - Risho
public class MyLinks : WebPart
{
public static string m_Portal = ConfigurationManager.ConnectionStrings["dbPortal"].ConnectionString;
Panel pnlMyLinks = new Panel();
Label lblError = new Label();
Label lblMyLinkURL = new Label();
Label lblMyLinkName = new Label();
TextBox txtMyLinkName = new TextBox();
TextBox txtMyLinkURL = new TextBox();
Button btnSaveMyLink = new Button();
LinkButton lbMyLinkAdd = new LinkButton();
Literal litP1 = new Literal();
Literal litBR1 = new Literal();
public cisf_MyLinks()
{
this.Title = "MyLinks";
this.ExportMode = WebPartExportMode.All;
}
protected override void CreateChildControls()
{
GetLinks();
base.CreateChildControls();
}
//protected override void OnPreRender(EventArgs e)
//{
// btnSaveMyLink.Text = "Save";
// btnSaveMyLink.Click += new EventHandler(btnSaveMyLink_Click);
// Controls.Add(btnSaveMyLink);
// base.OnPreRender(e);
//}
protected void GetLinks()
{
pnlMyLinks.Controls.Clear();
int i = 0;
lbMyLinkAdd.Text = "Add";
pnlMyLinks.Controls.Add(lbMyLinkAdd);
lbMyLinkAdd.Click += new EventHandler(lbMyLinkAdd_Click);
pnlMyLinks.Controls.Add(new LiteralControl("<br />"));
IDataReader drMyLinks = Get_MyLinks(Page.Request.ServerVariables["Logon_User"].Split("\\".ToCharArray())[1].ToLower());
while (drMyLinks.Read())
{
HyperLink hlMyLink = new HyperLink();
LinkButton lbDelMyLink = new LinkButton();
lbDelMyLink.Text = "(del)";
lbDelMyLink.ToolTip = "Delete this link";
lbDelMyLink.CssClass = "verytiny";
lbDelMyLink.Command += new CommandEventHandler(DelMyLink);
lbDelMyLink.CommandName = drMyLinks["id"].ToString();
pnlMyLinks.Controls.Add(lbDelMyLink);
pnlMyLinks.Controls.Add(new LiteralControl(" "));
hlMyLink.ID = "hl" + drMyLinks["ID"].ToString();
hlMyLink.Text = drMyLinks["Title"].ToString();
hlMyLink.NavigateUrl = drMyLinks["url"].ToString();
hlMyLink.Target = "_blank";
hlMyLink.ToolTip = drMyLinks["Title"].ToString();
pnlMyLinks.Controls.Add(hlMyLink);
pnlMyLinks.Controls.Add(new LiteralControl("<br />"));
if (drMyLinks["ID"].ToString() != "") { i += 1; }
}
this.Controls.Add(pnlMyLinks);
}
protected void lbMyLinkAdd_Click(object sender, EventArgs e)
{
lbMyLinkAdd.Visible = false;
lblMyLinkName.Visible = true;
txtMyLinkName.Visible = true;
litBR1.Visible = true;
lblMyLinkURL.Visible = true;
txtMyLinkURL.Visible = true;
btnSaveMyLink.Visible = true;
litP1.Visible = true;
(txtMyLinkName - dot focus)
lblMyLinkName.Text = "Link Name: ";
lblMyLinkURL.Text = "Link URL: ";
btnSaveMyLink.Text = "Save";
btnSaveMyLink.Click += new EventHandler(btnSaveMyLink_Click);
pnlMyLinks.Controls.Add(new LiteralControl("<table class='mylinksTable' cellpadding='0' cellspacing='0' border='1'><tr valign='top'><td>"));
pnlMyLinks.Controls.Add(lblMyLinkName);
pnlMyLinks.Controls.Add(new LiteralControl("</td><td>"));
pnlMyLinks.Controls.Add(txtMyLinkName);
pnlMyLinks.Controls.Add(new LiteralControl("</td></tr><tr valign='top'><td>"));
pnlMyLinks.Controls.Add(lblMyLinkURL);
pnlMyLinks.Controls.Add(new LiteralControl("</td><td>"));
pnlMyLinks.Controls.Add(txtMyLinkURL);
pnlMyLinks.Controls.Add(new LiteralControl("</td></tr><tr valign='top'><td colspan='2'>"));
pnlMyLinks.Controls.Add(btnSaveMyLink);
pnlMyLinks.Controls.Add(new LiteralControl("</td></tr></table>"));
this.Controls.Add(pnlMyLinks);
}
protected void btnSaveMyLink_Click(object sender, EventArgs e)
{
string thisURL;
if ((txtMyLinkName.Text != "") && (txtMyLinkURL.Text != ""))
{
if (txtMyLinkURL.Text.StartsWith("http"))
{ thisURL = txtMyLinkURL.Text; }
else { thisURL = "http://" + txtMyLinkURL.Text; }
AddMyLink(txtMyLinkName.Text, thisURL, Page.Request.ServerVariables["Logon_User"].Split("\\".ToCharArray())[1].ToLower());
GetLinks();
txtMyLinkName.Text = "";
txtMyLinkURL.Text = "";
lbMyLinkAdd.Visible = true;
}
lbMyLinkAdd.Visible = true;
lblMyLinkName.Visible = false;
txtMyLinkName.Visible = false;
litBR1.Visible = false;
lblMyLinkURL.Visible = false;
txtMyLinkURL.Visible = false;
btnSaveMyLink.Visible = false;
litP1.Visible = false;
}
}
If you are creating the button in code, then it needs to be wired up in the Page_Load event so that the click event can fire. Page_PreRender is too late.
In addition to adding the control in Load event as already posted, you should set the ID field e.g. btnSaveMyLink.ID = "SaveLink"; to a unique value.