I need to align button's text, horizontally left on C# WinForms application. All the buttons create dynamically. I tried few ways as bellow. But not worked.
private void dynBtnClick(string btnText) //Dynamic Text List In flp2
{
string[] listData = File.ReadAllLines(filePath + #"\" + btnText + ".txt");
int e=listData.Count();
flp2.FlowDirection = FlowDirection.LeftToRight;
flp2.Controls.Clear();
for ( int j =0; j<e;j++)
{
Guna.UI2.WinForms.Guna2Button iBtn = new Guna.UI2.WinForms.Guna2Button();
iBtn.Tag = j;
iBtn.BorderRadius = 5;
iBtn.Height = 25;
iBtn.Width = 200;
iBtn.AutoSize = false;
iBtn.Animated = true;
iBtn.FillColor = ColorTranslator.FromHtml("#263238");
iBtn.TextAlign = ContentAlignment.MiddleLeft;
string[] btnFacetext = listData[j].Split('~');
iBtn.Text = btnFacetext[0].ToString();
iBtn.Click += (s, c) => { flp2Action(btnFacetext[0]+"~"+ btnFacetext[1], btnText); };
flp2.Controls.Add(iBtn);
}
}
Not working for me.
iBtn.TextAlign = Left;
iBtn.TextAlign = ContentAlignment.MiddleLeft;
Here is the current button state (marked by red lines). Need to texts align left. Please help on this.
Guna.UI2.WinForms.Guna2Button.TextAlign is of type HorizontalAlignment not ContentAlignment
iBtn.TextAlign = HorizontalAlignment.Left;
Related
I wanna change the Text properties of Label using Buttons just like in hangman; but after I created the Label, I became confused when I try to access the specific Label
// creating label
for (int i = 0; i < numericUpDown1.Value; i++)
{
Label l = new Label();
l.Text = "_";
l.Width = 20;
l.Height = 25;
l.Left = i * 20 + 510;
l.Top = 20;
l.BackColor = Color.Transparent;
groupBox2.Controls.Add(l);
}
// function to change the label text
// if I clicked the button
// the first label text will be changed to the text in the button i clicked
private void B_Click(object sender, EventArgs e)
{
var thsBtn = (Button)sender;
bool benar = false;
if (benar == false)
{
thsBtn.Text = " ";
thsBtn.Enabled = false;
}
else
{
thsBtn.Enabled = false;
}
}
You can organize created Labels into a collection, say, List<Label>:
private List<Label> m_CreatedLabels = new List<Label>();
...
// Remove all previous labels
foreach (Label lbl in m_CreatedLabels)
lbl.Dispose();
m_CreatedLabels.Clear();
// Create new ones
for (int i = 0; i < numericUpDown1.Value; i++) {
m_CreatedLabels.Add(new Label() {
Text = "_",
Width = 20,
Height = 25,
Left = i * 20 + 510,
Top = 20,
BackColor = Color.Transparent,
Parent = groupBox2
});
}
Now you have m_CreatedLabels collection to work with created Labels, e.g.
private void B_Click(object sender, EventArgs e) {
var thsBtn = sender as Button;
// you may want to add a condition into FirstOrDefault(), e.g.
// .FirstOrDefault(lbl => lbl.Text == "_")
// - first label with "_" Text
Label lblToProcess = m_CreatedLabels
.FirstOrDefault();
if (null != lblToProcess)
lblToProcess.Text = thsBtn.Text;
thsBtn.Enabled = false;
}
One option here is to give your dynamically created Label instances a Name. From there, you should be able to use ControlCollection.Find to find your Label instances by name.
private void CreateLabels()
{
for (int i = 0; i < numericUpDown1.Value; i++)
{
Label l = new Label();
l.Name = $"DynamicLabel{i}";
l.Text = "_";
l.Width = 20;
l.Height = 25;
l.Left = i * 20 + 510;
l.Top = 20;
l.BackColor = Color.Transparent;
groupBox2.Controls.Add(l);
}
}
private void DoSomethingWithADynamicLabel(int dynamicLabelIndex)
{
Label l = groupBox2.Controls.Find($"DynamicLabel{i}", true).FirstOrDefault() as Label;
if (l is null)
{
// Couldn't find the label...
return;
}
// Do something with l
}
When creating the Label instances inside CreateLabels, I'm simply appending the for loop's counter to the string "DynamicLabel". This gives you a bunch of Labels with names like "DynamicLabel0", "DynamicLable1", "DynamicLabel2", etc...
Then in DoSomethingWithADynamicLabel, assuming you have the index of the Label you want to deal with, you can use groupBox2.Controls.Find to actually find the Label you're interested in. ControlCollection.Find returns Control[], so calling FirstOrDefault will take the first item from the array or null if no Control with the given name exists.
I tried to decrease space between space between columns and also wanted to decrease width of columns, but I was only able to adjust width of columns not space between columns.
please help for solution. I really appreciate the effort.
Code snap: `
for (int i = 0; i < dss.Tables[1].Rows.Count; i++)
{
yValues[i] = Convert.ToDouble(dss.Tables[1].Rows[i]["admission"].ToString());
if (isDateRange == 1)
{
xValues[i] = dss.Tables[1].Rows[i]["mth"].ToString().Substring(0, dss.Tables[1].Rows[i]["mth"].ToString().IndexOf(" "));
}
else
{
xValues[i] = dss.Tables[1].Rows[i]["mth"].ToString();
}
zValues[i] = Convert.ToDouble(dss.Tables[1].Rows[i]["readmission"].ToString());
}
chart1.Series[0].Points.DataBindXY(xValues, yValues);
chart1.Series[0].ToolTip = "#AXISLABEL: #VALY";
chart1.Series[0]["PieLabelStyle"] = "Outside";
chart1.Series[0]["PieDrawingStyle"] = "Concave";
chart1.Series[1].Points.DataBindXY(xValues, zValues);
chart1.Series[1].ToolTip = "#AXISLABEL: #VALY";
var chartArea_chart1 = chart1.ChartAreas[chart1.Series[0].ChartArea];
// enable autoscroll
chartArea_chart1.CursorY.AutoScroll = true;
// let's zoom to [0,blockSize] (e.g. [0,100])
chartArea_chart1.AxisX.ScaleView.Zoomable = true;
chartArea_chart1.AxisX.ScaleView.SizeType = DateTimeIntervalType.Number;
//chartArea_chart1.AxisY.ScaleView.Zoomable = true;
//chartArea_chart1.AxisY.ScaleView.SizeType = DateTimeIntervalType.Auto;
//chart1.Series[0].CustomProperties ="PixelPointWidth = 10";
//chart1.Series[0].CustomProperties = "PointWidth = 0.1";
int position = 0;
int size = 30;
chartArea_chart1.AxisX.ScaleView.Zoom(position, size);
// disable zoom-reset button (only scrollbar's arrows are available)
chartArea_chart1.AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;`
on startup I'm generating a lot of controls 90 to be exact and everything is working ok EXCEPT for the labels they are not being drawn or something? they are there because I can click them and they show proper ID (click event) here's the genereation code
private static bool ClientsLoaded = false;
private static WebBrowser[] Clients = new WebBrowser[45];
private static Label[] ClientLabel = new Label[45];
private static int MaximizedClient = -1;
public Form1()
{
InitializeComponent();
int WBoffsetX = 0;
int WBoffsetY = 0;
int lbloffsetX = 0;
int lbloffsetY = 0;
for (int i = 0; i < 45; i++)
{
var wb = new WebBrowser();
Clients[i] = wb;
wb.ScrollBarsEnabled = false;
wb.Height = 12;
wb.Width = 12;
wb.Location = new Point(2 + WBoffsetX, 2 + WBoffsetY);
WBoffsetX += 13;
wb.ScriptErrorsSuppressed = true;
this.Controls.Add(wb);
ClientLabel[i] = new Label();
ClientLabel[i].Name = "lbl_" + i;
ClientLabel[i].Font = new Font("Arial", 12);
ClientLabel[i].ForeColor = System.Drawing.Color.White;
ClientLabel[i].Location = new Point(12 + lbloffsetX, 450 + lbloffsetY);
lbloffsetX += 22;
ClientLabel[i].Click += new EventHandler(lbl_click);
ClientLabel[i].Text = "C" + i + ": o";
this.Controls.Add(ClientLabel[i]);
}
}
I've tried adding a button with for(45) clientlabel[i].Refresh() and it did nothing I tried changing the visibilty of them all to false and then back to true and nothing however I did find 1 thing interesting if I hide lbl_1 label 2 text will appear if I had label 2 label 3 text will appear but if I change the previous label back to visible they stay invisible textwise
I can click in a line on the form and
private void lbl_click(object sender, EventArgs e)
{
int id = -1;
var s = sender.ToString();
for(int i = 0; i<=45; i++)
{
if (s.Contains("C" + i + ":"))
{
id = i;
}
}
MessageBox.Show("Hello label, " + id);
}
will pop up the proper ids etc
does anyone know what's causing this maybe? or how to fix it
Well, I don't know what is the problem. This code works well enough and it has only marginal differences with the original(AutoSize property, explicit statement of Height and Width, and minor Location adjustment):
for (int i = 0; i < ClientLabel.Length; i++)
{
// Web browsers
WebBrowser wb = new WebBrowser()
{
ScrollBarsEnabled = false,
Height = 12,
Width = 12,
Location = new Point(2 + WBoffsetX, 2 + WBoffsetY),
ScriptErrorsSuppressed = true
};
WBoffsetX += 13;
Clients[i] = wb;
// Labels
Label label = new Label()
{
Name = "label_" + i,
Text = "Data",
AutoSize = true,
Location = new Point(50 + lbloffsetX, 50 + lbloffsetY),
Width = 100,
Height = 20,
Font = new Font("Arial", 12),
ForeColor = System.Drawing.Color.White,
};
label.Click += new EventHandler(lbl_click);
ClientLabel[i] = label;
lbloffsetX += 30;
}
this.Controls.AddRange(Clients);
this.Controls.AddRange(ClientLabel);
I am adding various dynamically created controls to a panel, based on what the user selects. If a Groupbox, with associated RadioButtons, is the first control, it looks fine:
...but if it's anything other than that, the associated radio buttons seem right-aligned instead of left-aligned, as seen above, and the groupbox is too wide, to boot.
Here is the pertinent code (RepaintMockupPanel() is called when the user opts to see what his mockup looks like at any time, and getGroupBox() is the method it calls that should be where the problem lies, but I can't see it.
private void RepaintMockupPanel(Control padre)
{
const string BTN = "BUTTON";
const string CKBX = "CHECKBOX";
const string EDTTXT = "EDITTEXT";
const string RADGRP = "RADIOGROUP";
const string SPNR = "SPINNER";
const string TXTVU = "TEXTVIEW";
const int LEFT_STARTING_POINT = 4;
const int STANDARD_PADDING = 4;
int currentLeft = LEFT_STARTING_POINT;
string currentSel;
string currentSettings;
ComboBox cmbx;
Label lbl;
try
{
TabPage tp = padre as TabPage;
string panelName = tp.Name.Replace("tabPage", "panel");
Panel p = tp.Controls[panelName] as Panel;
p.Controls.Clear();
for (int i = 0; i < p.Controls.Count; i++)
{
p.Controls[i].Dispose();
}
//cmbxRow0Element0 and lblRow0Element0 to cmbxRow11Element5 and lblRow11Element5
int rowNum = getRowNum(panelName);
for (int i = 0; i < WIDGETS_PER_TABPAGE; i++)
{
cmbx = tp.Controls[string.Format("cmbxRow{0}Element{1}", rowNum, i)] as ComboBox;
lbl = tp.Controls[string.Format("lblRow{0}Element{1}", rowNum, i)] as Label;
if (cmbx.SelectedIndex < 0) continue;
currentSel = cmbx.SelectedItem.ToString().ToUpper();
currentSettings = lbl.Text;
// Possible vals (Android on left, Windows equivalents on the right:
//Button ""
//CheckBox ""
//EditText TextBox
//RadioGroup GroupBox (w. RadioButtons nested within)
//Spinner ComboBox
//TextView Label
if ((currentSel.Length > 0) && (currentSettings.Length > 0))
{
if (currentSel.Equals(BTN))
{
Button btn = getButton(currentSettings, currentLeft);
p.Controls.Add(btn);
currentLeft += btn.Width + STANDARD_PADDING;
}
else if (currentSel.Equals(CKBX))
{
CheckBox ckbx = getCheckBox(currentSettings, currentLeft);
p.Controls.Add(ckbx);
currentLeft += ckbx.Width + STANDARD_PADDING;
}
else if (currentSel.Equals(EDTTXT))
{
TextBox txtbx = getTextBox(currentSettings, currentLeft);
p.Controls.Add(txtbx);
currentLeft += txtbx.Width + STANDARD_PADDING;
}
else if (currentSel.Equals(RADGRP))
{
GroupBox grpbx = getGroupBox(currentSettings, currentLeft);
p.Controls.Add(grpbx);
currentLeft += grpbx.Width + STANDARD_PADDING;
}
else if (currentSel.Equals(SPNR))
{
ComboBox cmbxDyn = getComboBox(currentSettings, currentLeft);
p.Controls.Add(cmbxDyn);
currentLeft += cmbxDyn.Width + STANDARD_PADDING;
}
else if (currentSel.Equals(TXTVU))
{
Label lblDyn = getLabel(currentSettings, currentLeft);
p.Controls.Add(lblDyn);
currentLeft += lblDyn.Width + STANDARD_PADDING;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private GroupBox getGroupBox(string currentSettings, int curLeftVal)
{
// "apple~orange~peach~True (must look for "enclose group in a black box" as the last val (ignore for the quick-and-dirty mockup, though))
// Adapted from Pierre's answer at http://stackoverflow.com/questions/23944419/why-is-only-the-first-radiobutton-being-added-to-the-groupbox
IList<string> grpbxVals = new List<string>(currentSettings.Split('~'));
GroupBox gb = new GroupBox { Height = 60, Location = new Point(curLeftVal, 0) };
gb.AutoSize = true;
int radButtonYVal = 0;
for (int i = 0; i < grpbxVals.Count() - 1; i++)
{
//gb.Controls.Add(new RadioButton { Text = grpbxVals[i], Location = new Point(curLeftVal, radButtonPosition) });
gb.Controls.Add(new RadioButton { Text = grpbxVals[i], Location = new Point(gb.Location.X+2, radButtonYVal) });
radButtonYVal += new RadioButton().Height;
}
return gb;
}
The getGroupBox() method is INDEED where the issue lies.
As a Container, GroupBox has its own canvas upon which its child controls are drawn, so when you create a control with an X value of 5, it means it's 5 from the left of the GroupBox, NOT from the left of the form. It's absolute value on the form would be it's own X value (say in this case 5) plus the X value of the GroupBox (which we'll assume has a Left value of 25) for an absolute positon of being 30 from the Left.
This is why your example shows the radio buttons pushed over so far: if you examine the distance between the left edge of the RadioButtons in relation to the left edge of their containing GroupBox, it should be about the same distance as the left edge of the GroupBox from the left edge of ITS container.
Why not use a TableLayoutPanel or FlowLayoutPanel to automatically position the controls, you can insert with fill dock the GroupBox.
Then you just need to add the controls to ... LayoutPanel and positioned automatically.
You have several options to control the rows and / or columns of the TableLayoutPanel
And as other controls to control flow into the FlowLayoutPanel
Here a example using layout panel, place a Button docked Top, and a empty TabControl docked Fill, and try this code
private void button1_Click(object sender, EventArgs e)
{
for (int t = 0; t < 4;t++ )
tabControl1.TabPages.Add(CreateTabPage(t));
}
private TabPage CreateTabPage(int t)
{
TabPage result = new TabPage()
{
Text=string.Format("TabPage {0}",t)
};
FlowLayoutPanel flp = new FlowLayoutPanel()
{
Dock = DockStyle.Fill,
AutoScroll = true,
};
for (int i = 0; i < 10; i++)
{
flp.Controls.Add(CreateGroupBox(i));
}
result.Controls.Add(flp);
return result;
}
private Control CreateGroupBox(int i)
{
GroupBox result = new GroupBox()
{
Text = string.Format("GroupBox {0}", i),
Width = 150,
Height = 100
};
FlowLayoutPanel flp = new FlowLayoutPanel()
{
Dock = DockStyle.Fill,
WrapContents = false,
AutoScroll = true,
FlowDirection=FlowDirection.TopDown
};
CreateRadios(flp, i);
result.Controls.Add(flp);
return result;
}
private void CreateRadios(FlowLayoutPanel flp, int i)
{
for (int c = 0; c < 10; c++) {
flp.Controls.Add(new RadioButton()
{
Text = string.Format("RadioButton {0} in {1}", c, i)
});
}
}
Tricycle Omnivore was right; this works:
int radButtonYVal = 4;
int leftVal = 4;
for (int i = 0; i < grpbxVals.Count() - 1; i++)
{
gb.Controls.Add(new RadioButton { Text = grpbxVals[i], AutoSize = true, Location = new Point(leftVal, radButtonYVal) });
radButtonYVal += new RadioButton().Height -4; // the "-4" is a kludge to scrunch the radiobuttons together a bit
}
There is string array contains some file location.
I am using a foreach loop, in which each loop i want to create a new radio button control.
without foreach code performs, but in loop only one control is adding.
Can anybody tell me why? and how I perform this.
Code:
string[] location =
{
#"C:\Program Files\Skype\Phone\Skype.exe",
#"C:\Program Files\iTunes\iTunes.exe",
#"C:\Program Files\Internet Explorer\iexplore.exe"
};
int i = 10;
foreach (string path in location)
{
if (File.Exists(path))
{
RadioButton rbList = new RadioButton();
rbList.AutoSize = false;
Icon icn;
icn = Icon.ExtractAssociatedIcon(path);
rbList.Image = icn.ToBitmap();
rbList.Height = 100;
rbList.Width = 50;
i = i + 30;
rbList.Location = new Point(100, i);
groupBox1.Controls.Add(rbList);
}
}
You set the height to 100 but increase the position by 30 only.
rbList.Height = 100;
...
i = i + 30;
rbList.Location = new Point(100, i);
You can decrease the height below 30:
rbList.Height = 30; //or smaller
or
increase the "i" more than 100:
i = i + 100; //or more than 100
rbList.Location = new Point(100, i);
Add
rbList.AutoSize = true;
And be sure your groupBox1 is large enough to display all your radio buttons.
Little bit of changes:
i = i + 100;
rbList.Location = new Point(100, i);
groupBox1.Controls.Add(rbList);
int space = 10;
groupBox1.Height += rbList.Height + space;
This work without alignment, alignment is yours.
int i = 10;
var radios = new[] { "", "", "" }
.Where(path => File.Exists(path))
.Select(path => new RadioButton
{
AutoSize = false,
Image = Icon.ExtractAssociatedIcon(path).ToBitmap(),
Height = 100,
Width = 50,
Location = new Point(100, (i = i + 30))
})
.ToArray();
groupBox1.Controls.AddRange(radios);