c# how to maintain created dynamic buttons at next startup - c#

i am facing a trouble for few days. I had create a dynamic buttons at runtime but it will disappear on the next startup. please help. below is my coding.
private void button1_Click(object sender, EventArgs e)
{
createNewTable createTable = new createNewTable();
DialogResult dResult = createTable.ShowDialog();
string table_name = "";
if (dResult == DialogResult.OK)
{
table_name = createTable.tableName;
createTable.Dispose();
}
else if (dResult == DialogResult.Cancel)
{
createTable.Dispose();
}
if(table_name != string.Empty){
Button textbox = new Button();
textbox.Name = "btn_" + table_name;
textbox.Text = table_name;
textbox.Height = 55;
textbox.Width = 123;
textbox.MouseDown += new MouseEventHandler(textbox_MouseDown);
textbox.MouseMove += new MouseEventHandler(textbox_MouseMove);
textbox.MouseUp += new MouseEventHandler(textbox_MouseUp);
textbox.ContextMenuStrip = contextMenuStrip1;
this.Controls.Add(textbox);
}
}
i had searched some info like using XMLSerialize/application settings but it dont provided any sample for me how to add dynamic button using XMLSerialize. please help..

Related

How to assign Tab Pages dynamically and add a single text box to store the data from text box into the database using c#

So I am creating forms using Visual Studio .NET.
I am stuck when I try to add tab pages dynamically on a button click which creates a text box in a new tab.
When I create multiple tabs I want to get the data from the text boxes of each newly created tabs and add it to the database. I am having problems as these text boxes have the same name as I create them dynamically. I am new to C# and I need help.
public void add()
{
aa.Add(txt.Text);
var a = 1;
var newTabPage = new TabPage()
{
Text = "Page"
};
txt = new System.Windows.Forms.TextBox();
this.tabControl1.TabPages.Add(newTabPage);
newTabPage.Controls.Add(this.txt);
System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
newTabPage.Controls.Add(lbl);
lbl.Text = "New";
txt.Name = "Get";
lbl.AutoSize = true;
lbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
lbl.Location = new System.Drawing.Point(7, 389);
lbl.Name = "label263";
lbl.Size = new System.Drawing.Size(871, 13);
lbl.TabIndex = 317;
lbl.Text = "AA";
newTabPage.Controls.Add(lbl);
}
private void txt_TextChanged(object sender, EventArgs e)
private void button1_Click_1(object sender, EventArgs e)
{
add();
string value = txt.Text;
aa.Add(value);
}
private void saveToolStripMenuItem2_Click(object sender, EventArgs e)
{
SqlCommand command;
string insert1 = #"insert into testing(test) values(#testingt)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
for(int i= 0;i<aa.Count;i++)
{
if (aa[i]!= "" && aa[i]!="New Box")
{
command = new SqlCommand(insert1, conn);
command.Parameters.AddWithValue(#"testingt", aa[i]);
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Maybe you can set the Name property to distinguish them when you create them by creating an increment variable.
int pagecount = 1;
private void btAddtab_Click(object sender, EventArgs e)
{
TabPage tabPage = new TabPage
{
Name = "Tabpage" + pagecount.ToString(),
Text = "Tabpage" + pagecount.ToString()
};
TextBox textBox = new TextBox
{
Name = "TextBox" + pagecount.ToString()
};
tabPage.Controls.Add(textBox);
tabControl1.TabPages.Add(tabPage);
pagecount++;
}
As for how to get the value of the specified TextBox, you can refer to the following code.
private void btGetValue_Click(object sender, EventArgs e)
{
foreach (TabPage page in tabControl1.TabPages)
{
foreach (Control control in page.Controls)
{
// get the first textbox's value
if (control is TextBox && control.Name == "TextBox1")
{
Console.WriteLine(((TextBox)control).Text);
}
}
}
}

C# Programmatically created richtextbox and get text value from button

Hope you can help - I have small issue with code.
I have programmatically create rich textbox and text populated from database - which is then added to a panel where I have another button programmatically created.
As displayed:
private void GetPending()
{
SQL = "SELECT notID,notNote FROM Notes WHERE notisActive = #notisActive AND notUser = #notuser ";
y = 3;
using (SqlConnection SQLCon = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand(SQL, SQLCon);
cmd.Parameters.Add(new SqlParameter("notIsActive", "Pending"));
cmd.Parameters.Add(new SqlParameter("notUser", lblUserName.Text));
try
{
SQLCon.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
//Main Panel
Panel pnlPendingNote = new Panel();
pnlPendingNote.Size = new System.Drawing.Size(315, 110);
pnlPendingNote.Location = new Point(3, y);
pnlPendingNote.BorderStyle = BorderStyle.FixedSingle;
pnlPendingNote.BackColor = Color.FromArgb(244, 244, 244);
// Button to Activate To Do
Button butActivateToDo = new Button();
butActivateToDo.Location = new Point(250, 10);
butActivateToDo.Size = new System.Drawing.Size(25, 25);
butActivateToDo.BackColor = Color.Transparent;
butActivateToDo.FlatStyle = FlatStyle.Flat;
butActivateToDo.FlatAppearance.BorderSize = 0;
butActivateToDo.FlatAppearance.MouseOverBackColor = Color.FromArgb(244, 244, 244);
butActivateToDo.Cursor = Cursors.Hand;
butActivateToDo.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.Activate_25));
pnlPendingNote.Controls.Add(butActivateToDo);
RichTextBox rxtNotes = new RichTextBox();
rxtNotes.Size = new System.Drawing.Size(307, 68);
rxtNotes.Location = new Point(3, 37);
rxtNotes.Text = (read["notNote"].ToString());
rxtNotes.ReadOnly = true;
rxtNotes.BorderStyle = BorderStyle.None;
rxtNotes.BackColor = Color.FromArgb(244, 244, 244);
pnlPendingNote.Controls.Add(rxtNotes);
pnlPendingNote.Name = "PenNote" + pendingcounter;
pnlPendingNote.Tag = read.GetInt32(0);
butActivateToDo.Name = "PenNote" + pendingcounter;
butActivateToDo.Tag = read.GetInt32(0);
rxtNotes.Name = "PenNote" + pendingcounter;
rxtNotes.Tag = read.GetInt32(0);
// Increase by 1
pendingcounter++;
// Create Double Click
butActivateToDo.Click += new EventHandler(NewbutActivateToDo_Click);
pnlPendingNote.DoubleClick += new EventHandler(NewPendingButton_DoubleClick);
// Add Pending Note size inside Panding Panel
pnlPending.Controls.Add(pnlPendingNote);
y = y + 112;
}
}
}
catch (System.Exception Error)
{
MessageBox.Show(Error.Message); // display error - if unable to connect to server
}
SQLCon.Close(); // close the sql connection
}
}
Which Works great - i have my panels, textbox and button created.
I then have this code :
private void NewbutActivateToDo_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
RichTextBox rxtNotes = (RichTextBox)sender;
for (int i = 1; i < pendingcounter; i++)
{
if (btn.Name == ("PenNote" + i))
{
MessageBox.Show(rxtNotes.Text.ToString());
break;
}
}
}
Which is working to a degree - it get's what panel i have clicked on & I get the ID which is stored in the tag.
Next I want to get the text value from the text box.
So i have added the
RichTextBox rxtNotes = (RichTextBox)sender;
this throws error :
{"Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.RichTextBox'."}
So I would like to get the RtxtBox value when I click a "ActivateToDo" button.
Hope this makes sense -
thanks
Store a reference to the associated RichTextBox in the Tag() property of your Button:
Button butActivateToDo = new Button();
...
RichTextBox rxtNotes = new RichTextBox();
...
butActivateToDo.Tag = rxtNotes
Now the RichTextBox can be retrieved in the handler:
private void NewbutActivateToDo_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
RichTextBox rxtNotes = (RichTextBox)btn.Tag;
...
}

Fail to call event click

I create some Buttons dynamically but when I'm trying to call the event click this doesn't get in, I make some break points to see if something went wrong and doesn't mark an error or something like that...
this is my code where I create and assign some type of data:
/*********************ASSIGN BUTTONS DINAMICALLY***********************/
protected void Assign_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);
Button Btn_clic = (Button)sender;
var name = Btn_clic.Text;
List.ListUsers listArea = new List.ListUsers();
List<Data.Area> Area = listArea.AreaList();
List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();
List<Button> Botones = new List<Button>();
var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();
foreach (var team in TeamFCH)
{
Button newButton = new Button();
newButton.CommandName = "Btn" + Convert.ToString(team);
newButton.ID = "Btn_" + Convert.ToString(team);
newButton.Text = team;
newButton.Click += Info_Click;
newButton.CommandArgument = name;
newButton.OnClientClick = "return ModalGood();";
Botones.Add(newButton);
GoodPanel.Controls.Add(newButton);
newButton.CssClass = "btn-primary outline separate";
}
}
/**********************************************************************/
and here is where I try to call the event previously declared:
void Info_Click(object sender, EventArgs e)
{
Button Btnclick = (Button)sender;
var team = Btnclick.Text;
string name = Btnclick.CommandArgument;
List.ListUsers listArea = new List.ListUsers();
List<Data.Area> Area = listArea.AreaList();
List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();
var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
Grv_Eng.DataSource = ListOfToolsOk;
Grv_Eng.DataBind();
}

if user start typing in textbox value change to input else if user didn't type any thing value change to an specific string in C#

I have a listview and created a textbox to search itmes in that list!
everything is ok about searching!
but problem is I want my search box to be like this:
at first Searchbox.Text="Search ..." and if user started typing in that searchbox change to that keyword! else(if) searchbox got empty Searchbox.Text change to "Search ..." again!
maybe it's a little complicated! but i tried 1-2 hours on it! and couldn't make it!
I have used Timers,checkboxchange event,booleans,...! but couldn't make it! :(
Please Help!
*my Searchbox name here is textbox1.
Some Codes I tested:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string str = textBox1.Text;
/*
if (!keywordentered_bool)
{
textBox1.Text = "";
}
*/
if (str != "")
{
//Doing Search operations!
search_bool = true;
}
else
{//Doing Search operations!
search_bool = true;
// keywordentered_checkbox.Checked = true;
Searchtextbox_Timer.Interval = 100;
Searchtextbox_Timer.Enabled = true;
Searchtextbox_Timer.Tick += Searchtextbox_Timer_Tick;
//textBox2.Visible = false;
}
}
else
{
if (search_bool)
{
listView1.Items.Clear();
label1.Visible = false;
listView1.Items.AddRange(Originalplaylist_list.ToArray());
if (!search_bool)
{
listView1.Items[MusicLogindex_list[MusicLogindex_list.Count - 1]].ForeColor = Color.Cyan;
}
else if (search_bool)
{//Doing Search operations
search_bool = false;
Searchtextbox_Timer.Interval = 100;
Searchtextbox_Timer.Enabled = true;
Searchtextbox_Timer.Tick += Searchtextbox_Timer_Tick;
//textBox2.Visible = true;
// keywordentered_checkbox.Checked = false;
}
}
void Searchtextbox_Timer_Tick(object sender, EventArgs e)
{
if (!search_bool)
{
textBox2.Visible = true;
textBox2.Location = textBox1.Location;
//textBox1.Text = "Search ...";
//textBox1.ForeColor = Color.Gray;
//textBox1.Font = new Font(textBox1.Font, FontStyle.Italic);
}
else
{
textBox2.Visible = false;
// textBox1.Text = "";
// textBox1.ForeColor = Color.Black;
// textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
}
Searchtextbox_Timer.Enabled = false;
//throw new NotImplementedException();
}
This is just psuedocode but the concept is there and you need to implement the text change event for searching , you can do additional changes in event handler.
Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";
myTxtbx.OnFocus += OnFocus.EventHandle(RemoveText);
myTxtbx.LoseFocus += LoseFocus.EventHandle(AddText);
public RemoveText(object sender, EventArgs e)
{
myTxtbx.Text = "";
}
public AddText(object sender, EventArgs e)
{
if(string.IsNullorEmpty(myTxtbx.Text))
myTxtbx.Text = "Enter text here...";
}
This is an example shows for a dynamic textbox control, you can add these events to your control and use the same code for make it work.
Or you can use this plugin
Visual Studio gallery plugin
Another plugin you can use for this purpose
Textbox with placeholder
Hope this helps.
thanks to #Frebin Francis my problem solved!
I downloaded the source code from this link TextBox With Placeholder
and added it to my project! then add it to my form and yeah! :)

Click event of dynamically created Button not firing

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.

Categories

Resources