Selecting a default combobox value - c#

When my program loads, my combobox has no default value. I want the first one to be the default value when the program is loaded. How can I do that?
using Gtk;
using System;
class SharpApp : Window
{
Label label;
Label label2;
Label label3;
Label label4;
public SharpApp() : base(" VALUTASOFFAN")
{
SetDefaultSize(411, 199);
SetPosition(WindowPosition.Center);
SetIconFromFile("..\\..\\web.png");
DeleteEvent += new DeleteEventHandler(OnDelete);
string[] valutor = new string[]
{
"YEN",
"SEK",
"EURO"
};
//BOX1
Fixed fix = new Fixed();
ComboBox cb = new ComboBox(valutor);
ComboBox cb2 = new ComboBox(valutor);
Entry entry = new Entry ();
Entry entry2 = new Entry ();
cb.Changed += OnChanged;
cb2.Changed += OnChanged2;
entry.Changed += onChanged3;
entry2.Changed += onChanged4;
ComboBox combo = ComboBox.NewText();
combo.Active = 0
cb.Active = 0;
label = new Label("-");
label2 = new Label("-");
label3 = new Label("-");
label4 = new Label("-");
fix.Put(entry, 100, 30);
fix.Put(entry2, 100, 100);
fix.Put(cb, 300, 30);
fix.Put(cb2, 300, 100);
//fix.Put(label3, 10, 30);
//fix.Put(label4, 10, 100);
Add(fix);
ShowAll();
}
void OnChanged(object sender, EventArgs args)
{
ComboBox cb = (ComboBox) sender;
label.Text = cb.ActiveText;
}
void OnChanged2(object sender2, EventArgs args)
{
ComboBox cb2 = (ComboBox) sender2;
label2.Text = cb2.ActiveText;
}
void onChanged3(object sender3, EventArgs args)
{
Entry entry = (Entry)sender3;
label3.Text = entry.Text;
}
void onChanged4(object sender4, EventArgs args)
{
Entry entry2 = (Entry)sender4;
label4.Text = entry2.Text;
}
public static void Main()
{
Application.Init();
new SharpApp();
Application.Run();
}
void OnDelete(object obj, DeleteEventArgs args)
{
Application.Quit();
}
}

I want the first one to be the default value when the program is
loaded. How can I do that?
Base of index of the given items
yourComboBox.SelectedIndex = 0;
Base of .ValueMember of the ComboBox
yourComboBox.SelectedValue = 1;

Related

Call object after created by action in C# Winform

I have an action for my button in c# Winform like this:
private void btnAction_Click(object sender, EventArgs e)
{
TextBox tbxdg = new TextBox();
tbxdg.Name = "tbx_DG" + cx.ToString();
tbxdg.Location = new Point(508, 12 + (40 * cx));
tbxdg.Size = new Size(200, 24);
tbxdg.Font = new Font("Tahoma", 10);
panel2.Controls.Add(tbxdg);
cx++;
}
Now I want to get text from the textbox that i've created by clicking my button. I've tried call the textbox by the name that i given to it in the button click action but it's not working.
u can try this:
var textBoxText = panel2.Controls.Find("name of textbox", false).First().Text;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int cx = 0;
private void button1_Click(object sender, EventArgs e)
{
TextBox tbxdg = new TextBox();
tbxdg.Name = "tbx_DG" + cx.ToString();
tbxdg.Location = new Point(0, 0 + (40 * cx));
tbxdg.Size = new Size(200, 24);
tbxdg.Font = new Font("Tahoma", 10);
panel1.Controls.Add(tbxdg);
cx++;
}
private void button2_Click(object sender, EventArgs e)
{
label1.Text = string.Empty;
foreach (TextBox tb in panel1.Controls)
{
label1.Text += $"{tb.Name} - {tb.Text}\n";
}
}
}
Demo
Instead of searching the control name in the panel, another approach is to add all the dynamic text boxes to global List<TextBox>
Please read comments inside the example:
private int cx;
private List<TextBox> DynamicTextBoxesList = new List<TextBox>();
private void btnAction_Click(object sender, EventArgs e)
{
TextBox tbxdg = new TextBox();
tbxdg.Name = "tbx_DG" + cx.ToString();
tbxdg.Location = new Point(508, 12 + (40 * cx));
tbxdg.Size = new Size(200, 24);
tbxdg.Font = new Font("Tahoma", 10);
panel2.Controls.Add(tbxdg);
// add to list
DynamicTextBoxesList.Add(tbxdg);
cx++;
}
// button event for example how to use DynamicTextBoxesList
private void btnExampleFoaccesingTextBoxes_Click(object sender, EventArgs e)
{
if (DynamicTextBoxesList.Count > 0)
{
foreach (TextBox t in DynamicTextBoxesList)
{
MessageBox.Show(t.Text);
}
// or you can find by name for example you need cx=1:
var txtbox = DynamicTextBoxesList.Where(x => x.Name == "tbx_DG1").FirstOrDefault();
if (txtbox != null)
{
MessageBox.Show(txtbox.Text);
}
}
}

field with a button in the DataGridView

I have a bounded DataGridView. How can I add a button in one field with data? I will attach a screenshot of how I see it. Do you have any recommendations on this?
it's WinForms and I think that I need to write a custom column type.
I don't think the standard DataGridViewColumn subclasses provide what you're after.
It can be done, though: you will have to create your own custom Control (I guess a TextBox with a Button right next to it), and the appropriateDataGridViewColumn and DataGridViewCell subclasses to host your custom control.
Follow the documentation for further details.
Of course, the alternative would be using third-party, smarter grids.
Create custom column:
class TextAndButtonControl : UserControl
{
private TextBox textbox1;
private Button button1;
public TextAndButtonControl()
{
this.textbox1 = new TextBox();
this.Controls.Add(this.textbox1);
this.button1 = new Button();
this.Controls.Add(this.button1);
this.RenderControl();
this.button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hi");
}
public string Text
{
get { return this.textbox1.Text; }
set { this.textbox1.Text = value; }
}
public string ButtonText
{
get { return this.button1.Text; }
set { this.button1.Text = value; }
}
public void RenderControl()
{
this.textbox1.Location = new Point(0, 0);
this.textbox1.Width = 2 * this.Width / 3;
this.textbox1.Height = this.Height;
this.button1.Location = new Point(2 * this.Width / 3, 0);
this.button1.Width = this.Width / 3;
this.button1.Height = this.Height;
}
}
Add the control in the following way
private void Form1_Load(object sender, EventArgs e)
{
TextAndButtonControl bcol = new TextAndButtonControl();
bcol.Text = "Button Column ";
bcol.ButtonText = "Click Me";
bcol.Name = "btnClickMe";
bcol.RenderControl();
dgMainGrid.Controls.Add(bcol);
}
There is a DataGridViewButtonColumn-Type (Or if you just want a single Cell as Button -> DataGridViewButtonCell-Type).
You could create the DataGridButtonColumn and then add it to your DataGridView:
DataGridViewButtonColumn tempBtnColumn = new DataGridViewButtonColumn();
tempBtnColumn.HeaderText = "Button";
tempBtnColumn.Text = "Button-Text";
tempBtnColumn.Name = "Button-Name";
tempBtnColumn.UseColumnTextForButtonValue = true;
Grid.Columns.Add(tempBtnColumn);
//or if you want a specified position for the Grid:
Grid.Columns.Insert(0, tempBtnColumn);
Update
Here is an update, you could give the ButtonCell the Value you want and then read that with CurrentCell.Value (here is a example, hope it's understandable):
private void ButtonCellWithValue()
{
DataGridViewButtonCell dgvbc = new DataGridViewButtonCell();
dgvbc.Value = "1";
DataGridViewRow dgvr = new DataGridViewRow();
dgvr.Cells.Add(dgvbc);
dataGridView1.Rows.Add(dgvr);
dgvbc = new DataGridViewButtonCell();
dgvbc.Value = "2";
dataGridView1.Rows[0].Cells[1] = dgvbc;
GridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick);
}
void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (((DataGridView)sender).CurrentCell.Value == "1")
{
MessageBox.Show("Super");
}
else if (((DataGridView)sender).CurrentCell.Value == "2")
{
MessageBox.Show("Better");
}
}
Thank a lot #RavirajPalvankar.
If somebody will need, I will write the code here, because cann't write it to Ravuraj's comment, because it's long:
Use the class as Raviraj write:
class TextAndButtonControl : UserControl
{
private TextBox textbox1;
private Button button1;
public TextAndButtonControl()
{
this.textbox1 = new TextBox();
this.Controls.Add(this.textbox1);
this.button1 = new Button();
this.Controls.Add(this.button1);
this.renderControl();
this.button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Click! The value is:" + this.Text);
}
public string Text
{
get { return this.textbox1.Text; }
set { this.textbox1.Text = value; }
}
public string ButtonText
{
get { return this.button1.Text; }
set { this.button1.Text = value; }
}
public void renderControl()
{
this.textbox1.Location = new Point(0, 0);
this.textbox1.Width = 2 * this.Width / 3;
this.textbox1.Height = this.Height;
this.button1.Location = new Point(2 * this.Width / 3, 0);
this.button1.Width = this.Width / 3;
this.button1.Height = this.Height;
}
}
then in main Form:
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
for (int j = 0; j < 20; j++)
{
dt.Rows.Add("col1" + j.ToString(), "col2" + j.ToString());
}
this.dataGridView1.DataSource = dt;
this.dataGridView1.Columns[0].Width = 150;
this.txbtnControl = new TextAndButtonControl();
this.txbtnControl.Visible = false;
this.dataGridView1.Controls.Add(this.txbtnControl);
//Handle the cellbeginEdit event to show the usercontrol in the cell while editing
this.dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
}
TextAndButtonControl txbtnControl;
void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex > -1 && e.RowIndex != this.dataGridView1.NewRowIndex)
{
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
this.txbtnControl.Location = rect.Location;
this.txbtnControl.Size = rect.Size;
this.txbtnControl.Text = this.dataGridView1.CurrentCell.Value.ToString();
this.txbtnControl.ButtonText = "...";
this.txbtnControl.renderControl();
this.txbtnControl.Visible = true;
}
}

How to dynamically create buttons and add events to them?

I have array of buttons, and array of labels:
Label[] labels = new Label[10];
Button[] but = new Button[10];
While clicking the other button I want to dynamically create new button and new label from the array, i also want the but[i] to change the tex of labels[i]:
private void button1_Click(object sender, EventArgs e)
{
labels[i] = new Label();
labels[i].Location = new System.Drawing.Point(0, 15+a);
labels[i].Parent = panel1;
labels[i].Text = "Sample text";
labels[i].Size = new System.Drawing.Size(155, 51);
labels[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
a = labels[i].Height + labels[i].Top;
but[i] = new Button();
but[i].Text = "-";
but[i].Location = new System.Drawing.Point(0, labels[i].Height + labels[i].Top);
but[i].Parent = panel1;
but[i].Size = new System.Drawing.Size(155, 10);
but[i].Click += new System.EventHandler(but_Click);
i++;
}
private void but[i]_Click(object sender, EventArgs e)
{
labels[i].Text = "Changed Text";
}
But apparently I can't put an array in an event handler, how should I do it then?
One way to do this is to make your method return a handler instead of being a handler:
private EventHandler but_Click(int i)
{
return (s, e) => labels[i].Text = "Changed Text";
}
And use it like:
but[i].Click += but_Click(i);
Or do it inline:
but[i].Click += (s, ea) => labels[i].Text = "Changed Text";
What's happening in either of these is some compiler magic to capture the i variable. It's equivalent to this (which is also a valid, if verbose, way to do it):
class MyWrapper {
private int i;
public MyWrapper(int i) {
this.i = i;
}
public void TheHandler(object sender, EventArgs e) {
// TODO: capture the object that owns `labels` also, or this won't work.
labels[i].Text = "Changed Text";
}
}
//call with
but[i].Click += new EventHandler(new MyWrapper(i).TheHandler);
You could add the array index to the button as Tag property, and then pull it back out in but_Click.
So, add
but[i].Tag = i;
to the button creation. And then change the event handler:
private void but_Click(object sender, EventArgs e)
{
int buttonIndex = (int)((Button)sender).Tag;
labels[buttonIndex].Text = "Changed Text";
}
Or put the event handler inline:
but[i].Click += (s,e) => { label[i].Text = "Changed Text"; }
Or another option using the Tag property, add:
but[i].Tag = label[i];
...
private void but_Click(object sender, EventArgs e)
{
Label label = (Label)((Button)sender).Tag;
label.Text = "Changed Text";
}
Advantage of this approach is you're not relying on keeping arrays in synch after the initial creation of the controls.
I guess this is self-explaining:
public void SomeMehthod()
{
Button btn1 = new Button();
Button btn2 = new Button();
Button btn3 = new Button();
// Your button-array
Button[] btns = new Button[]
{
btn1,
btn2,
btn3
};
foreach(Button btn in btns)
{
// For each button setup the same method to fire on click
btn.Click += new EventHandler(ButtonClicked);
}
}
private void ButtonClicked(Object sender, EventArgs e)
{
// This will fire on any button from the array
// You can switch on the name, or location or anything else
switch((sender as Button).Name)
{
case "btn1":
// Do something
break;
case "btn2":
// Do something
break;
case "btn3":
// Do something
break;
}
}
Or if your array is accessible globaly:
Button[] btns = new Button[5];
Label[] lbls = new Label[5];
private void ButtonClicked(Object sender, EventArgs e)
{
Button clicked = sender as Button;
int indexOfButton = btns.ToList().IndexOf(clicked);
// ..IndexOf() returns -1 if nothign is found
if(indexOfButton > 0)
{
lbls[indexOfButton].DoWhatYouWant...
}
}

Dynamically Created Combobox's SelectedIndexChanged Event

i'm designing a windows form application. In this app, user selects a number from a combobox, then depending on the number, some dynamic controls will be created(labels and comboboxes).
My problem is, i need to write some code on these dynamically created comboboxs' "selectedindexchanged" event. But i don't know how to create an event to dynamic combobox.
Here is my function:
FORM1.CS
public void getchildCntrl(Panel pnl,ComboBox cmbb)
{
for (int ix = pnl.Controls.Count - 1; ix >= 0; ix--)
if (pnl.Controls[ix].Name.Substring(0, 5) == "Child") pnl.Controls[ix].Dispose();
if (cmbb.SelectedIndex != 0)
{
Label[] childLabels = new Label[cmbb.SelectedIndex];
ComboBox[] txtTeamNames = new ComboBox[cmbb.SelectedIndex];
for (int i = 0; i < txtTeamNames.Length; i++)
{
//label create
var lbl = new Label();
childLabels[i] = lbl;
lbl.Name = "ChildLb" + i.ToString();
lbl.Text = (i + 1).ToString() + ". Çocuk-Yaş :";
lbl.Width = 80;
lbl.Location = new Point(cmbb.Location.X - 85, cmbb.Location.Y + 7 + ((i + 1) * 28));
lbl.Visible = true;
pnl.Controls.Add(lbl);
//combobox create
var cmb = new ComboBox();
txtTeamNames[i] = cmb;
cmb.Name = "Child" + i.ToString();
cmb.Location = new Point(cmbb.Location.X, cmbb.Location.Y + 5 + ((i + 1) * 28));
cmb.Width = 40;
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.DataSource = ages.ToArray();
cmb.Visible = true;
pnl.Controls.Add(cmb);
}
}
}
You just register to the event like below...
cmb.SelectedIndexChanged += new System.EventHandler((object o, EventArgs e) =>
{
//Do something here
});
Or
cmb.SelectedIndexChanged += new System.EventHandler(cmb_SelectedValueChanged);
private void cmb_SelectedValueChanged(object sender, EventArgs e)
{
//Do something here.
}
You can hook up an event handler to the ComboBox like this:
cmd.SelectionChanged += new SelectionChangedEventHandler(GuiController_SelectionChanged);
void GuiController_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
throw new NotImplementedException();
}
Register event handler this way:
cmb.SelectedIndexChanged+=new EventHandler(cmb_SelectedIndexChanged);
Unregister this way:
cmb.SelectedIndexChanged-=new EventHandler(cmb_SelectedIndexChanged);
private void cmb_SelectedIndexChanged(object sender, System.EventArgs e)
{
//write your event code here
}
How to: Create Event Handlers at Run Time for Windows Forms
public void getchildCntrl(Panel pnl,ComboBox cmbb)
{
//// your code.....
//combobox create
var cmb = new ComboBox();
cmb.SelectedIndexChanged+=new EventHandler(cmb_SelectedIndexChanged);
// remaining code
cmb.Visible = true;
pnl.Controls.Add(cmb);
}
}
}
For specifying parameters - go through:
ComboBox.SelectedIndexChanged Event

Unable to update Label in prompt box

I am working on the following code:
private Label textLabel;
public void ShowDialog()
{
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 150;
prompt.Text = caption;
textLabel = new Label() { Left = 50, Top=20, Text="txt"};
TextBox textBox = new TextBox() { Left = 50, Top=50, Width=400 };
Button confirmation = new Button() { Text = "Ok", Left=350, Width=100, Top=70 };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.ShowDialog();
}
I am calling the above method using another method and trying to update the textLabel field inside a loop like this
public void doIt()
{
ShowDialog();
for(int i=0;i<10;i++)
{
textLabel.TEXT = ""+i;
Threading.Thread.Sleep(1000);
}
}
That is the way we do in Java, but in C# it I could not update the label text in this way. What is wrong here and why can't I update the text?
So this is how I would do it, it is not a complete solution but I hope it will point you in the right direction:
Make the Prompt class that will derive from the Form. Add the controls to it (I did it manually but you could use the designer). Add the Timer which will be triggered on each second and which will change the label's text. When the counter hits 10 stop the timer.
public partial class Prompt : Form
{
Timer timer;
Label textLabel;
TextBox textBox;
Button confirmation;
int count = 0;
public Prompt()
{
InitializeComponent();
this.Load += Prompt_Load;
this.Width = 500;
this.Height = 150;
textLabel = new Label() { Left = 50, Top = 20, Text = "txt" };
textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70 };
this.Controls.Add(confirmation);
this.Controls.Add(textLabel);
this.Controls.Add(textBox);
timer = new Timer();
timer.Interval = 1000;
timer.Tick += timer_Tick;
}
void Prompt_Load(object sender, EventArgs e)
{
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
this.textLabel.Text = " " + count.ToString();
count++;
if (count == 10)
timer.Stop();
}
}
In the doIt method, create the instance of your Prompt form, set its caption and call its ShowDialog() method.
public void doIt()
{
Prompt p = new Prompt();
p.Text = caption;
p.ShowDialog();
}

Categories

Resources