C# Programmatically created richtextbox and get text value from button - c#

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

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

How to create EventHandler for dynamically created buttons (for each one) C# VS2010

So, I have a form in which all buttons and textboxes and labes are dynamically generated
Code:
private void LoadElements()
{
int Y = 30;
int j = 0;
con.Open();
OleDbCommand populate = new OleDbCommand("SELECT * FROM Users", con);
OleDbDataReader reader = populate.ExecuteReader();
while (reader.Read())
{
b = new Button();
b.Text = "Delete";
b.Name = reader["Username"].ToString();
b.BackColor = Color.DarkOrange;
b.ForeColor = Color.Black;
b.Location = new Point(240, Y);
b.FlatStyle = FlatStyle.Flat;
LB.Add(b);
tb1 = new TextBox();
tb1.Location = new Point(10, Y);
TB1.Add(tb1);
tb1.Text = reader["Username"].ToString();
tb2 = new TextBox();
tb2.Location = new Point(120, Y);
tb2.Text = reader["Password"].ToString();
TB2.Add(tb2);
Y += 30;
j++;
}
foreach (Button BTN in LB) // <- this is a globaly declared List<Button>
{
this.Controls.Add(BTN);
BTN.Click += new EventHandler(BTN_Click);
}
foreach (TextBox text1 in TB1) // <= -||- List<TextBox>
{ this.Controls.Add(text1); }
foreach (TextBox text2 in TB2) // -||-
{ this.Controls.Add(text2); }
// MORE CODE UNDER
}
As you may or may not have noticed, the whole form is a "superadmin" type of form, all users and passwords are loaded from database onto it. I want to be able to have a reference to the created buttons, when a Delete button is clicked I want the program to go into the database and search "WHERE [Username] LIKE" + button.Name + ""(because the button name is the actually Username); My code creates elements dynamically like this: [Name] [Password] [Delete] in the form of [textbox1] [textbox2] [button]. Problem is whenever I click any of the buttons it only takes reference to the last one created, how could I make the event handler so that it can see every button's respective .name?
The pivotal code is in the event handling procedure - you did not show that. Look at the object sender parameter, and use it accordingly!
void BTN_Click(object sender, EventArgs e)
{
Button b = sender as Button;
if (b!=null)
{
//that's your button, with the properties created in the loop.
}
}
It looks like your looking for this code.
b.Click += new EventHandler(b_Click);
Add it into your button creation...
while (reader.Read())
{
b = new Button();
b.Text = "Delete";
b.Name = reader["Username"].ToString();
b.BackColor = Color.DarkOrange;
b.ForeColor = Color.Black;
b.Location = new Point(240, Y);
b.FlatStyle = FlatStyle.Flat;
***b.Click += new EventHandler(b_Click);***
LB.Add(b);
}

How to fit picture and text inside a flowlayoutpanel with a dynamically created radiobutton in c#

I have a program that displays a candidate running in a position. Example President. I made a all my controls dynamic. I created a FlowLayoutPanel and inside is a RadioButton which has a .Text of the candidate.
My code :
private void FPreview_Load(object sender, EventArgs e)
{
PanelPresident();
}
FlowLayoutPanel PresPanel = new FlowLayoutPanel();
private void PanelPresident()
{
Label PresLabel = new Label();
PresLabel.Text = "PRESIDENT";
PresLabel.AutoSize = true;
PresLabel.Location = new Point(50, 210);
PresLabel.Font = new Font(this.Font, FontStyle.Bold);
PresLabel.Font = new Font("Courier New", 15);
PresLabel.ForeColor = Color.Aquamarine;
this.Controls.Add(PresLabel);
PresPanel.Size = new Size(160, 300);
PresPanel.Location = new Point(30, 240);
PresPanel.FlowDirection = FlowDirection.TopDown;
PresPanel.BorderStyle = BorderStyle.FixedSingle;
PresPanel.AutoScroll = true;
PresPanel.BackColor = Color.Maroon;
PresPanel.WrapContents = false;
Controls.Add(PresPanel);
PresPanel.SuspendLayout();
try
{
string cmdPres = "SELECT (LastName + ', ' + FirstName + ' ' + MiddleName) as PresName, " +
"imgPath as PresImagePath, " + "id as PresID FROM TableVote WHERE Position='President'";
using (SqlCommand Prescom = new SqlCommand(cmdPres, sc))
{
if (sc.State != ConnectionState.Open) sc.Open();
SqlDataReader Presreader = Prescom.ExecuteReader();
while (Presreader.Read())
{
PresRadioButton(Presreader.GetString(0), Presreader.GetString(1), Presreader.GetInt32(2));
}
Presreader.Close();
sc.Close();
PresPanel.ResumeLayout(true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void PresRadioButton(string PresName, string PresimagePath, int PresID)
{
RadioButton Presradio = new RadioButton { Text = PresName, Parent = PresPanel };
Presradio.AutoSize = false;
Presradio.Size = new Size(130, 130);
Presradio.Image = new Bitmap(Image.FromFile(PresimagePath), 90, 90);
Presradio.TextImageRelation = TextImageRelation.ImageAboveText;
Presradio.CheckAlign = ContentAlignment.BottomCenter;
Presradio.ImageAlign = ContentAlignment.MiddleCenter;
Presradio.TextAlign = ContentAlignment.MiddleCenter;
Presradio.ForeColor = Color.LimeGreen;
Presradio.Tag = PresID;
}
My Problem is, if the Text of radiobutton is long, the picture wont fit. it does not show the full picture. Can you help me fix this problem by fitting my picture inside the flowlayoutpanel even though the text is long. Thanks :)

How do I use the save feature on tabcontols?

I have a form where I can add tabs into a tabcontrol by pressing a button on the form. There are 4 textboxes and then the name of the tab. I have added using system.io;
Where would I even start to create a save for all of the tabs? I have the save button created, I just don't know where to start. I would guess I would need a loop of some kind.
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public string status = "no";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string name = txtName.Text;
//validate information
try { }
catch { }
//create new tab
string title = name;
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
//Add Labels
Label lb = new Label();
lb.Text = "Denomination:";
lb.Location = new System.Drawing.Point(150, 75);
lb.Name = "lbl";
lb.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb);
Label lb2 = new Label();
lb2.Text = "Year:";
lb2.Location = new System.Drawing.Point(150, 120);
lb2.Name = "lbl2";
lb2.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb2);
Label lb3 = new Label();
lb3.Text = "Grade:";
lb3.Location = new System.Drawing.Point(150, 165);
lb3.Name = "lbl3";
lb3.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb3);
Label lb4 = new Label();
lb4.Text = "Mint Mark:";
lb4.Location = new System.Drawing.Point(150, 210);
lb4.Name = "lbl4";
lb4.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb4);
//Add text boxes
TextBox tb = new TextBox();
tb.Location = new System.Drawing.Point(250, 75);
tb.Name = "txt";
tb.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb);
TextBox tb1 = new TextBox();
tb1.Location = new System.Drawing.Point(250, 120);
tb1.Name = "txt1";
tb1.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb1);
TextBox tb2 = new TextBox();
tb2.Location = new System.Drawing.Point(250, 165);
tb2.Name = "txt2";
tb2.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb2);
TextBox tb3 = new TextBox();
tb3.Location = new System.Drawing.Point(250, 210);
tb3.Name = "txt3";
tb3.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb3);
//put data inside of textboxes
tb.Text = txtCoin.Text;
tb1.Text = txtYear.Text;
tb2.Text = txtGrade.Text;
tb3.Text = txtMint.Text;
// Add delete button
Button bn = new Button();
bn.Location = new System.Drawing.Point(560, 350);
bn.Name = "btnDelete";
bn.Text = "Delete";
bn.Size = new System.Drawing.Size(100, 50);
bn.Click += MyClick;
myTabPage.Controls.Add(bn);
}
private void MyClick(object sender, EventArgs e)
{
Form2 myform = new Form2();
myform.ShowDialog();
if (status == "yes")
{ tabControl1.TabPages.Remove(tabControl1.SelectedTab); }
status = "no";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
int counter;
int ccounter;
string outLine;
string pathFileName = Path.Combine(Application.StartupPath, "coins.dat");
StreamWriter writeIt = new StreamWriter(pathFileName);
for (counter = 0; ((tabControl1.TabCount) -1) != 0 ;)
{
}
writeIt.Close();
}
}
}
Use a foreach loop instead of your for (counter = 0; ((tabControl1.TabCount) -1) != 0 ;) loop:
foreach (TabPage tabPage in tabControl.TabPages)
Your for loop is a infinite loop, do it like that:
for (counter = 0; counter < tabControl1.TabCount; counter++)
{
// Save the tab
}

c# saving tabs using system.io;

I have the below code. I think I have pretty close to what I need. There is a main tab at startout (which does not contain tb, tb1, tb2, and tb3. Once I click the button, a tab is generated containing tb, tb1, tb2, tb3.
tb, tb1,tb2, and tb3 show errors of not existing. I simply cannot figure out how to get these saved.
public partial class Form1 : Form
{
public string status = "no";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string name = txtName.Text;
//validate information
try { }
catch { }
//create new tab
string title = name;
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
//Add Labels
Label lb = new Label();
lb.Text = "Denomination:";
lb.Location = new System.Drawing.Point(150, 75);
lb.Name = "lbl";
lb.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb);
Label lb2 = new Label();
lb2.Text = "Year:";
lb2.Location = new System.Drawing.Point(150, 120);
lb2.Name = "lbl2";
lb2.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb2);
Label lb3 = new Label();
lb3.Text = "Grade:";
lb3.Location = new System.Drawing.Point(150, 165);
lb3.Name = "lbl3";
lb3.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb3);
Label lb4 = new Label();
lb4.Text = "Mint Mark:";
lb4.Location = new System.Drawing.Point(150, 210);
lb4.Name = "lbl4";
lb4.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb4);
//Add text boxes
TextBox tb = new TextBox();
tb.Location = new System.Drawing.Point(250, 75);
tb.Name = "txt";
tb.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb);
TextBox tb1 = new TextBox();
tb1.Location = new System.Drawing.Point(250, 120);
tb1.Name = "txt1";
tb1.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb1);
TextBox tb2 = new TextBox();
tb2.Location = new System.Drawing.Point(250, 165);
tb2.Name = "txt2";
tb2.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb2);
TextBox tb3 = new TextBox();
tb3.Location = new System.Drawing.Point(250, 210);
tb3.Name = "txt3";
tb3.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb3);
//put data inside of textboxes
tb.Text = txtCoin.Text;
tb1.Text = txtYear.Text;
tb2.Text = txtGrade.Text;
tb3.Text = txtMint.Text;
// Add delete button
Button bn = new Button();
bn.Location = new System.Drawing.Point(560, 350);
bn.Name = "btnDelete";
bn.Text = "Delete";
bn.Size = new System.Drawing.Size(100, 50);
bn.Click += MyClick;
myTabPage.Controls.Add(bn);
}
private void MyClick(object sender, EventArgs e)
{
Form2 myform = new Form2();
myform.ShowDialog();
if (status == "yes")
{ tabControl1.TabPages.Remove(tabControl1.SelectedTab); }
status = "no";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
int counter;
int ccounter;
string outLine ;
string pathFileName = Path.Combine(Application.StartupPath, "coins.dat");
StreamWriter writeIt = new StreamWriter(pathFileName);
foreach (TabPage tabPage in tabControl1.TabPages)
{
if (tabControl1.TabCount > 1)
{
outLine = tabPage + tb.Text + tb1.Text + tb2.Text + tb3.Text + "\t";
writeIt.WriteLine(outLine);
}
if (tabControl1.TabCount == 1)
{
outLine = tabPage + "\t";
writeIt.WriteLine(outLine);
}
}
writeIt.Close();
}
}
}
You need to store tb1, etc in fields in your form so they can be accessed by other methods.
tb, tb1,tb2, and tb3 show errors of not existing.
Yes, they would - you're declaring them as local variables within button1_Click. To access them from other methods, you'll either need to just examine the controls within the tab page, or declare them as instance variables instead. However, in that case you'd need to consider the fact that there may be multiple tab pages.
It sounds like you really just need to iterate over the controls within each tab page, and pick out the textboxes. Either that, or perhaps create your own subclass of TabPage which knows about the textboxes. Then you could find each instance of your custom TabPage and ask it to save itself.

Categories

Resources