I have a button which I added programmatically and I want to store certain unique information with every button. I have saved the Name and Text but is there a way to store another string to access later. Below is the code for my button and it's click event.
for (int i = bankaccountsDatagridview.Rows.Count - 1; i >= 0; i--)
{
string buttonName = "individualDepartmentBtn-" + i;
FontAwesome.Sharp.IconButton individualDepartmentBtn = new FontAwesome.Sharp.IconButton();
individualDepartmentBtn.BackColor = System.Drawing.Color.White;
individualDepartmentBtn.Cursor = System.Windows.Forms.Cursors.Hand;
individualDepartmentBtn.Dock = System.Windows.Forms.DockStyle.Top;
individualDepartmentBtn.FlatAppearance.BorderSize = 0;
individualDepartmentBtn.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Silver;
individualDepartmentBtn.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
individualDepartmentBtn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
individualDepartmentBtn.Flip = FontAwesome.Sharp.FlipOrientation.Normal;
individualDepartmentBtn.Font = new System.Drawing.Font("Roboto", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
individualDepartmentBtn.ForeColor = System.Drawing.Color.DimGray;
individualDepartmentBtn.IconChar = FontAwesome.Sharp.IconChar.None;
individualDepartmentBtn.IconColor = System.Drawing.Color.DimGray;
individualDepartmentBtn.IconSize = 25;
individualDepartmentBtn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
individualDepartmentBtn.Margin = new System.Windows.Forms.Padding(10);
individualDepartmentBtn.Padding = new System.Windows.Forms.Padding(30, 0, 0, 0);
individualDepartmentBtn.Name = bankaccountsDatagridview.Rows[i].Cells[1].Value.ToString();
individualDepartmentBtn.Rotation = 0D;
individualDepartmentBtn.Size = new System.Drawing.Size(192, 30);
individualDepartmentBtn.TabIndex = 1;
individualDepartmentBtn.Text = bankaccountsDatagridview.Rows[i].Cells[1].Value.ToString();
individualDepartmentBtn.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
individualDepartmentBtn.UseVisualStyleBackColor = false;
navigationPanel.Controls.Add(individualDepartmentBtn);
individualDepartmentBtn.MouseDown += new System.Windows.Forms.MouseEventHandler(individualBankBtnDown);
}
Click Event:
private void individualBankBtnDown(object sender, MouseEventArgs e)
{
bankTitle = ((FontAwesome.Sharp.IconButton)sender).Name.ToString();
}
You can use the Tag property. For example:
individualDepartmentBtn.Tag = "My String";
You can store any object within Tag and not only strings.
Note that you could also use the var keyword and an object initializer to make your code a little bit more readable:
var individualDepartmentBtn = new FontAwesome.Sharp.IconButton
{
BackColor = System.Drawing.Color.White,
Cursor = System.Windows.Forms.Cursors.Hand,
Dock = System.Windows.Forms.DockStyle.Top,
...
};
Related
I am trying to make a Windows Form that shows display data from data a table. Every thing is working fine until I start scrolling in the Form using the auto scroll property.
I don't know why that's happening. I hope someone can help me.
private void allShowsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
// Load All the Shows from the database
DataTable dt = accesse.LoadAllShows();
// Create the allShows From
Form allShows = new Form();
// Create the Controls for the AllShows form.
PictureBox[] pic = new PictureBox[dt.Rows.Count];
Label[] showName = new Label[dt.Rows.Count], season = new Label[dt.Rows.Count], eps = new Label[dt.Rows.Count], typ = new Label[dt.Rows.Count];
TextBox[] txtShowName = new TextBox[dt.Rows.Count], txtSeason = new TextBox[dt.Rows.Count], txtEps = new TextBox[dt.Rows.Count], txtTyp = new TextBox[dt.Rows.Count];
// AllShows Form properties
allShows.BackColor = Color.White;
allShows.Font = new Font("Calibri", 14f, FontStyle.Regular);
allShows.ForeColor = Color.Black;
allShows.Size = new Size(1050, 700);
allShows.StartPosition = FormStartPosition.CenterScreen;
allShows.AutoScroll = true;
allShows.AutoScrollMargin = new Size(0, 18);
// Variables
int y = 325; // the distens bettwen the controls on the Y and X.
bool xTurn = false; // the axies turn.
int yTurnNum = 0; // the y turn number.
for (int i = 0; i < dt.Rows.Count; i++)
{
// PictureBox Poster Properties
pic[i] = new PictureBox();
pic[i].BorderStyle = BorderStyle.FixedSingle;
pic[i].Size = new Size(162, 288);
pic[i].SizeMode = PictureBoxSizeMode.StretchImage;
pic[i].Image = Image.FromFile(dt.Rows[i][4].ToString());
// Label showName Properties
showName[i] = new Label();
showName[i].Text = "Show Name: " + dt.Rows[i][0];
showName[i].AutoSize = true;
// Label Season Properties
season[i] = new Label();
season[i].Text = "Season: " + dt.Rows[i][1];
season[i].AutoSize = true;
// Label Eps Properties
eps[i] = new Label();
eps[i].Text = "Episodes: " + dt.Rows[i][2];
eps[i].AutoSize = true;
// Label Typ Properties
typ[i] = new Label();
typ[i].Text = "Typ: " + dt.Rows[i][3];
typ[i].AutoSize = true;
if (xTurn)
{
// Sitting the location of the controls on the X turn
pic[i].Location = new Point(515, pic[i - 1].Location.Y);
showName[i].Location = new Point(687, showName[i - 1].Location.Y);
season[i].Location = new Point(687, season[i - 1].Location.Y);
eps[i].Location = new Point(687, eps[i - 1].Location.Y);
typ[i].Location = new Point(687, typ[i - 1].Location.Y);
xTurn = false;
}
else
{
// Sitting the location of the controls on the Y turn
pic[i].Location = new Point(15, 15 + (yTurnNum * y));
showName[i].Location = new Point(187, 20 + (yTurnNum * y));
season[i].Location = new Point(187, 55 + (yTurnNum * y));
eps[i].Location = new Point(187, 90 + (yTurnNum * y));
typ[i].Location = new Point(187, 125 + (yTurnNum * y));
yTurnNum += 1;
xTurn = true;
}
allShows.Controls.Add(pic[i]);
allShows.Controls.Add(showName[i]);
allShows.Controls.Add(season[i]);
allShows.Controls.Add(eps[i]);
allShows.Controls.Add(typ[i]);
}
allShows.ShowDialog();
}
catch (Exception ex)
{
tools.ShowErrorMessageBox(ex.Message, "Error");
}
}
I hope this gif will help you to understand what is happening.
enter image description here
I'm attempting to display some dynamically generated labels next to dynamically generated text boxes. The text boxes appear but the labels do not.
I've looked at several solutions and have tried to make sure I defined all the label properties. I looked at some threading related solution that seem unnecessary because i'm not changing visibility state, I would just like to pop up the labels next to the text boxes.
TextBox[] channelNames = new TextBox[numOfChannels];
GroupBox channelBox = new GroupBox();
Label[] labelNames = new Label[numOfChannels];
for (int currentChannelIndex = 0; currentChannelIndex < numOfChannels; currentChannelIndex++)
{
var txt = new TextBox();
channelNames[currentChannelIndex] = txt;
txt.Name = channelCollection[currentChannelIndex].PhysicalName;
txt.Text = "ben";
txt.Location = new Point(200, 32 + (currentChannelIndex * 28));
txt.Visible = true;
this.channelBox.Controls.Add(channelNames[currentChannelIndex]);
var lbl = new Label();
labelNames[currentChannelIndex] = lbl;
lbl.AutoSize = true;
lbl.Name = channelCollection[currentChannelIndex].PhysicalName;
lbl.Size = new Size(55, 13);
lbl.TabIndex = 69;
lbl.Text = channelCollection[currentChannelIndex].PhysicalName;
lbl.Location = new Point(175, 32 + (currentChannelIndex * 28));
lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.channelBox.Controls.Add(labelNames[currentChannelIndex]);
}
Here are a few things to check:
1) You are setting "AutoSize" and "Size". Trying removing "Size"
2) The default font is likely too large for the (55,13) size.
Try explicitly setting the font to something small to see if it shows up.
Does channelCollection[currentChannelIndex].PhysicalName actually contain a non-Empty string? e.g.:
class Something
{
public string PhysicalName { get; set; }
}
private void AddLabels()
{
Something[] channelCollection = new Something[]
{
//Applying this to Label.Text makes it "invisible"
new Something() { PhysicalName = "" }
};
var currentChannelIndex = 0;
var txt = new TextBox();
txt.Name = channelCollection[currentChannelIndex].PhysicalName;
txt.Text = "ben";
txt.Location = new Point(200, 32);
txt.Visible = true;
this.Controls.Add(txt);
var lbl = new Label();
lbl.AutoSize = true;
lbl.Name = channelCollection[currentChannelIndex].PhysicalName;
lbl.Size = new Size(55, 13);
lbl.TabIndex = 69;
lbl.Text = channelCollection[currentChannelIndex].PhysicalName;
lbl.Location = new Point(175, 32);
lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.Controls.Add(lbl);
}
I actually had an exception that downstream of this code block that was causing the issue. I assumed that i would see the labels since the exception was thrown after the call to the label. Thanks for your suggestions.
I have an add user button which dynamically adds a remove button and a username textbox when the user clicks it. The user can click the button as many times as they like and the controls will continue to add.
I am having trouble with the remove button that is created dynamically. It should removed the itself and the username textbox next to it. Instead it will always remove the top row that was added. Also when you click add a new user after you have clicked remove it doesn't automatically fill the blank space - it moves the new textbox and button to the bottom line.
Here is my code:
private void AddUserbtn_Click_1(object sender, EventArgs e)
{
TextBox[] Username = new TextBox[n];
Button[] Remove = new Button[n];
int UsernameX, UsernameY, RemoveX, RemoveY;
UsernameX = 346;
UsernameY = 45;
RemoveX = 946;
RemoveY = 45;
for (int i = 0; i < n; i++)
{
Username[i] = new TextBox();
Username[i].Size = new Size(233, 26);
Username[i].Location = new Point(UsernameX, UsernameY + space);
Username[i].Font = new Font("Arial", 10);
Username[i].Name = "Username" ;
Remove[i] = new Button();
Remove[i].Location = new Point(RemoveX, RemoveY + space);
Remove[i].Text = "Remove";
Remove[i].Font = new Font("Arial", 10);
Remove[i].Size = new Size(95, 23);
Remove[i].UseVisualStyleBackColor = true;
Remove[i].Click += new EventHandler(Remove_Click);
Remove[i].Name = "Remove";
space += 35;
}
for (int i = 0; i < n; i++)
{
CaeUsersPanel.Controls.Add(Username[i]);
CaeUsersPanel.Controls.Add(Remove[i]);
}
}
private void Remove_Click(object sender, EventArgs e)
{
CaeUsersPanel.Controls.Remove(CaeUsersPanel.Controls[("Username")]);
CaeUsersPanel.Controls.Remove(CaeUsersPanel.Controls[("Remove")]);
}
Put a class variant to store Button - TextBox pair, and delete respectively. Quick tested code below - not fine tuned for memory leak / logic etc, just a sample code that fulfills your requirement.
Dictionary<Button, TextBox> pair = new Dictionary<Button, TextBox>(); // A dictionary to store the Button - TextBox pair
private void button1_Click(object sender, EventArgs e) {
int n = 3; // Added for testing
int space = 0; // Added for testing
int UsernameX, UsernameY, RemoveX, RemoveY;
UsernameX = 100; // Modified for testing
UsernameY = 45;
RemoveX = 400; // Modified for testing
RemoveY = 45;
for (int i = 0; i < n; i++) {
var Username = new TextBox();
Username.Size = new Size(233, 26);
Username.Location = new Point(UsernameX, UsernameY + space);
Username.Font = new Font("Arial", 10);
Username.Name = "Username";
var Remove = new Button();
Remove.Location = new Point(RemoveX, RemoveY + space);
Remove.Text = "Remove";
Remove.Font = new Font("Arial", 10);
Remove.Size = new Size(95, 23);
Remove.UseVisualStyleBackColor = true;
Remove.Click += new EventHandler(Remove_Click);
Remove.Name = "Remove";
Controls.Add(Username);
Controls.Add(Remove);
pair.Add(Remove, Username);
space += 35;
}
}
private void Remove_Click(object sender, EventArgs e) {
Controls.Remove((Button)sender); // Removes the delete button
Controls.Remove(pair[(Button)sender]); // Removes the textbox
pair.Remove((Button)sender); // Removes the entry in dictionary
}
Update: Another version for better memory and logic matters. Also shifts up the rest of controls up if it's the OP's desire.
int n = 3; // Added for testing, probably you already have it somewhere
int space = 0; // Added for testing, probably you already have it somewhere
// Moved for logic
// Value modified for testing
int UsernameX = 100;
int UsernameY = 45;
int RemoveX = 400;
int RemoveY = 45;
int SpaceDelta = 35; // Added for logic
List<Button> RemoveButtons = new List<Button>();
List<TextBox> UsernameTextBoxes = new List<TextBox>();
private void button1_Click(object sender, EventArgs e) {
Random rnd = new Random((int)DateTime.Now.Ticks); // Added for testing
for (int i = 0; i < n; i++) {
var Username = new TextBox();
Username.Size = new Size(233, 26);
Username.Location = new Point(UsernameX, UsernameY + space);
Username.Font = new Font("Arial", 10);
Username.Name = "Username";
Username.Text = $"{(int)(rnd.NextDouble() * 100000)}"; // Added for testing
var Remove = new Button();
Remove.Location = new Point(RemoveX, RemoveY + space);
Remove.Text = $"{(int)(rnd.NextDouble() * 100000)}"; // Modified for testing
Remove.Font = new Font("Arial", 10);
Remove.Size = new Size(95, 23);
Remove.UseVisualStyleBackColor = true;
Remove.Click += new EventHandler(Remove_Click);
Remove.Name = "Remove";
Controls.Add(Username);
Controls.Add(Remove);
RemoveButtons.Add(Remove);
UsernameTextBoxes.Add(Username);
space += SpaceDelta;
}
}
private void Remove_Click(object sender, EventArgs e) {
int idx = RemoveButtons.IndexOf((Button)sender);
// Remove button
RemoveButtons[idx].Dispose();
RemoveButtons.RemoveAt(idx);
// Remove textbox
UsernameTextBoxes[idx].Dispose();
UsernameTextBoxes.RemoveAt(idx);
// Shift controls up
for (int i = idx; i < RemoveButtons.Count; i ++) {
RemoveButtons[i].Top -= SpaceDelta;
UsernameTextBoxes[i].Top -= SpaceDelta;
}
space -= SpaceDelta;
}
Remove the two last created :
private void Remove_Click(object sender, EventArgs e)
{
this.Controls.Remove(this.Controls[this.Controls.Count - 1]);
this.Controls.Remove(this.Controls[this.Controls.Count - 1]);
}
I'm currently working on a file explorer.
Now I want to change the ForeColor of one label.
But as soon as I add the code for it everything else disappears.
lblpath.ForeColor = ColorTranslator.FromHtml("00ff00");
When I start the application Form1 will just be empty.
I don't know if I should post my code, because it's quite a bit and I don't know which parts would be relevant...
EDIT:
Method where I use this code:
private void initiateGUI()
{
this.Text = "Explorer";
this.BackColor = ColorTranslator.FromHtml("#1a1a1a");
oneup = new Button();
oneup.Location = new Point(455, 12);
oneup.Parent = this;
oneup.Visible = true;
oneup.MouseClick += oneup_click;
oneup.Text = "UP";
oneup.Width = 40;
oneup.Height = 20;
cmdrefresh = new Button();
cmdrefresh.Location = new Point(500, 12);
cmdrefresh.Parent = this;
cmdrefresh.Visible = true;
cmdrefresh.MouseClick += refresh_click;
cmdrefresh.Text = "Refresh";
cmdrefresh.Width = 55;
cmdrefresh.Height = 20;
lblfolder.Location = new Point(475, 39);
lblfolder.Font = font;
//lblfolder.ForeColor = Color.Blue;
lblfolder.Parent = this;
lblfolder.Height = 13;
lblfolder.Text = "Folders";
lblfile.Location = new Point(12, 39);
lblfile.Font = font;
//lblfile.ForeColor = ColorTranslator.FromHtml("#00ff00");
lblfile.Parent = this;
lblfile.Height = 13;
lblfile.Text = "Files";
lblpath.Location = new Point(12, 15);
lblpath.Font = font;
lblpath.ForeColor = ColorTranslator.FromHtml("#00ff00");
lblpath.Parent = this;
lblpath.Height = 13;
lblpath.Width = 30;
lblpath.Text = "Path";
scrollfolder.AutoScroll = false;
scrollfolder.HorizontalScroll.Enabled = false;
scrollfolder.HorizontalScroll.Visible = false;
scrollfolder.HorizontalScroll.Maximum = 0;
scrollfolder.AutoScroll = true;
scrollfolder.Parent = this;
scrollfolder.Height = 390;
scrollfolder.Width = 220;
scrollfolder.Location = new Point(x2 - 10, y - 10);
scrollfiles.AutoScroll = false;
scrollfiles.HorizontalScroll.Enabled = false;
scrollfiles.HorizontalScroll.Visible = false;
scrollfiles.HorizontalScroll.Maximum = 0;
scrollfiles.AutoScroll = true;
scrollfiles.Parent = this;
scrollfiles.Height = 390;
scrollfiles.Width = 420;
scrollfiles.Location = new Point(x - 10, y - 10);
}
You are missing # in color definition. It should be:
lblpath.ForeColor = ColorTranslator.FromHtml("#00ff00");
ColorTranslator.FromHtml will throw exception if "00ff00" used
Why don't you use the designer to set the colour?
Where did you add this code, to the constructor? Most likely, the statement throws an exception before InitializeComponents gets a chance to run - and if you added the code to the constructor, before InitializeComponents, it's very likely that lblpath doesn't exist yet, so you're getting NullReferenceException. Try enabling "break on all exceptions" in the debugger, it's very handy for debugging Winforms applications, since the error will no longer be swallowed.
Use the designer to set the colour, and you'll be fine.
I have two labels next to each other. The values of these labels are changed at run time.
Now if the text of first label is long then it overlaps the second label.
What i want is the second label to shift right to avoid overlaping.
Is this possible?
Here is my code:
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.BackColor = System.Drawing.Color.Transparent;
this.labelName.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelName.ForeColor = System.Drawing.Color.White;
this.labelName.Location = new System.Drawing.Point(6, 1);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(93, 16);
this.labelName.TabIndex = 55;
this.labelName.Tag = "useHeaderImage Core";
this.labelName.Text = "Name";
//
// labelShareSize
//
this.labelShareSize.AutoSize = true;
this.labelShareSize.BackColor = System.Drawing.Color.Transparent;
this.labelShareSize.Font = new System.Drawing.Font("Tahoma", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
this.labelShareSize.ForeColor = System.Drawing.Color.White;
this.labelShareSize.Location = new System.Drawing.Point(206, 3);
this.labelShareSize.Name = "labelShareSize";
this.labelShareSize.Size = new System.Drawing.Size(46, 11);
this.labelShareSize.TabIndex = 56;
this.labelShareSize.Tag = "useHeaderImage Core";
this.labelShareSize.Text = "ShareSize";
Thanks
One approach could be to adjust the position of labelShareSize when the size of labelName changes. Here's some example code using the SizeChanged event to do this.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// attach this event handler before the text/size changes
labelName.SizeChanged += labelName_SizeChanged;
labelName.Text = "really really really really long text gets set here.........................";
}
void labelName_SizeChanged(object sender, EventArgs e)
{
AdjustLabelPosition();
}
private void AdjustLabelPosition()
{
if (labelShareSize.Left < labelName.Location.X + labelName.Width)
labelShareSize.Left = labelName.Location.X + labelName.Width;
}
}