I started out C# very recently and sorry if this question sounds dumb.
How do I add a Listbox in a Form that pops out from a Button click?
Note: The Form isn't the one that's added from the Solution Explorer whereby I can just drag a Listbox from the Toolbox to my Form.
So what I want is to create a ListBox in my file drawer1Form where I can add additional items. Thanks for the help in advance!:)
private void drawer1button_Click(object sender, EventArgs e) // Drawer 1 Button
{
drawer1Form df1 = new drawer1Form();
df1.StartPosition = FormStartPosition.CenterScreen;
df1.Show();
}
public partial class drawer1Form : Form // Creates drawer1Form
{
public drawer1Form()
{
Text = "Drawer 1 ";
}
}
Pretty much the same way as you'd do with any other object.
In the class of your form add a
private ListBox myAwesomeListBox;
Then in the button event handler add something like this:
myAwesomeListBox = new ListBox();
myAwesomeListBox.SuspendLayout();
// set all the properties that you want
myAwesomeListBox.Name = "myAwesomeListBox";
myAwesomeListBox.Location = new Point(...); // place it somewhere
myAwesomeListBox.Size = new Size(...); // give it a size
// etc...
df1.Controls.Add(myAwesomeListBox);
myAwesomeListBox.ResumeLayout();
This should be it.
I highly advise you to do it through the designer first though, and then take a look at the generated code in the form's .Designer.cs file, you'll have a very good understanding after reading through that.
Related
I am new to C#. I am using windows forms and I have Form1 which contains 2 buttons ( one to create user control at run time and the other creates buttons on user control at run time).
This code creates user control and FlowLayoutPanel (to organize button position) if you click add_UserControl button. And then it creates buttons on FlowLayoutPanel if you click Add_Buttons button and it is all done at run time.
Now in Form1 let's say I created user control and FlowLayoutPanel and then created 5 buttons , how can I save the properties/details of this user control with its FlowLayoutPanel and 5 buttons in SQL database so I can use them later when I run the program? I have been thinking about an idea and I reached the internet but no luck.
Any idea? Please help me. Thank you
public partial class Form1 : Form
{
FlowLayoutPanel FLP = new FlowLayoutPanel();
UserControl uc = new UserControl();
private void add_UserControl_Click(object sender, EventArgs e)
{
uc.Height = 700;
uc.Width = 900;
uc.BackColor = Color.Black;
Controls.Add(uc); //add UserControl on Form1
FLP.Height = 600;
FLP.Width = 800;
FLP.BackColor = Color.DimGray;
uc.Controls.Add(FLP); // add FlowLayoutPanel to UserControl
}
private void Add_Buttons_Click(object sender, EventArgs e)
{
//####### add buttons to FlowLayoutPanel ############
Button dynamicButton = new Button();
dynamicButton.Height = 50;
dynamicButton.Width = 200;
dynamicButton.BackColor = Color.Green;
dynamicButton.ForeColor = Color.Blue;
dynamicButton.Text = "";
FLP.Controls.Add(dynamicButton);
}
}
OK, First you need to create a class that will represent one of the buttons with the properties you need.
class MyButton
{
public string ButtonText {get;set;}
}
Everytime you click and create a button, you actually create an object of this class and add it to a collection or list. Then you would have some other code watching over the collection, and every time it gets a new entry, it creates a new button and sets its Button text to the text property. when a member of list is gone, it removes the button.
If you need more properties to be remembered (color, size, font, ...) you add them to the class as well. If you need for other controls, as well, .... you can always create common parent controls.
Simple.
If you want to be able to reload it, you could define the MyButton class as serializable and store it in xml file, and upon build, reload it.
You should watch into WPF and it's MVVM pattern. It's pretty much similar to it. Also have a look into command pattern, usefull pattern when it commes to this.
You can remember the FlowLayoutsPanels in one SQL table and in another table you could save the buttons which belong to these FlowLayoutPanels.
On Form Load or Application Load, you could check if there are already FlowLayoutPanels and correspending Buttons do exist in the SQL db and if yes then create them, else do nothing.
I have a User Control that contains a combobox/drop down list. This user control is used multiple times and added dynamically to a panel. When I change the value of the combobox on one user control, it changes the rest? Does anyone know how to sort this?
So to clarify. When I change the value in the combobox of the top usercontrol (7002), it will change the second user controls combobox value to whatever I selected.
Thanks!
Code for adding the controls;
foreach (Common.UserDTO UDTO in BLL.User.GetAllUsers())
{
Admin_UserControls.UserBar UB = new Admin_UserControls.UserBar(UDTO);
UB.Location = new Point(0, int.Equals(pnlUserBlock.Controls.Count, 0) ? 0 : pnlUserBlock.Controls[pnlUserBlock.Controls.Count - 1].Bottom);
pnlUserBlock.Controls.Add(UB);
}
constructor/load events:
private Common.UserDTO UDTO;
public UserBar(Common.UserDTO UDTO)
{
InitializeComponent();
/* Store the passed in UserDTO */
this.UDTO = UDTO;
}
private void UserBar_Load(object sender, EventArgs e)
{
/* Setup the Drop down list */
cbRanks.DataSource = Common.Helper.GetRanksDT();
cbRanks.DisplayMember = "Rank";
cbRanks.ValueMember = "ID";
/* Setup the users */
lblUsername.Text = UDTO.Username;
cbRanks.SelectedValue = UDTO.RankID;
}
Put the above comment into an answer should others have the same issue in future.
Each instance of the UserControl that is created is bound to the same DataSet giving you this result.
Caused by the line:
cbRanks.DataSource = Common.Helper.GetRanksDT();
To resolve this simply declare a new instance each time the UserControl is created, see this post that discusses a few methods.
I want to make my click event change an ApplicationBarIconButton. My ApplicationBarIconButton looks like this:
<shell:ApplicationBarIconButton x:Name="driveAction" Click="drive_click" IconUri="/img/car.png" Text="kör" />
I want the IconUri to change from /img/car.png to ex. /img/car-stop.png and the text value from kör to passagera. I tried the function below, but it only causes my app to shut down.
private void drive_click(object sender, EventArgs e)
{
this.driveAction.Text = "passagera";
this.driveAction.Source = "/img/car-stop.png";
}
What is wrong? Why doesn't this work?
The default ApplicationBar requires you to access the buttons through the ApplicationBar object. To accomplish this you must know the index of the button that you want to change
private const int DriveButtonIndex = 0;
private void drive_click(object sender, EventArgs e)
{
var button = (ApplicationBarIconButton)ApplicationBar.Buttons[DriveButtonIndex];
button.IconUri = new Uri("/img/car-stop.png", UriKind.Relative);
button.Text = "passagera";
}
There are a few custom ApplicationBars that allow you to name your buttons. But I've found that the above solution always works for me.
Get it directly from the application bar list -
ApplicationBar.Buttons[0].Text = "passagera";
ApplicationBar.Buttons[0].Source = "/img/car-stop.png";
You could also query the list of buttons for a specific icon as a more tenable long-term solution, but if you only have one button and that's not going to change, this works.
Because the ApplicationBarIconButton is actually a native control and not a true XAML object you cannot refer to it by name.
You can refer to it by index if create in XAML. Alternatively you could create it in code and then you can maintain a named reference you can use.
I have a WPF main window, which contains a toolbar with buttons and a tabcontrol that is displaying a page with a listbox. The page is hosted on a frame, and the frame is set on the tab I selected.
When I click on a button on my toolbar, a new window pops up with a textbox and a submit button. When I press the submit button, I want to insert the textbox contents into the listbox that's on the main window. However, nothing displays in the listbox. I tried listbox.Items.Add() but it still won't display.
public partial class AddNewCamper : Window
{
public AddNewCamper()
{
InitializeComponent();
}
private void btnNewSubmit_Click(object sender, RoutedEventArgs e)
{
CampersPage c;
// Converting string to int b/c thats what camper() takes in.
int NewAge = Convert.ToInt16(txtNewAge.Text);
int NewGrade = Convert.ToInt16(txtNewGrade.Text);
// Create a new person
Camper person = new Camper(NewAge, NewGrade, txtNewFirstName.Text);
txtNewFirstName.Text = person.getName();
// Trying to add the first name of the person to display on the listbox of another window.
c.testListBox.Items.Add(txtNewFirstName.Text);
}
You can follow any of the following approaches. But based on your comments I guess solution 3 suits you.
1) Try initializing c first. You can't use an object without allocating memory for it.
2) If you want to use the same object, use the reference of the object created in the MainWindow
in the required class.
something like this should work:
CampersPage c = [reference to CampersPage object in MainWindow]
then add items to your listbox
3) If you want to use the listbox object, make your CampersPage Class static.
Making it static would not require you to initialize your class explicitly.
public static CampersPage {
// do something here
}
Make sure that you declare your listbox in CampersPage as public.
Then in the class requiring your listbox defined in CampersPage, do the following
CampersPage.testListBox.Items.Add(txtNewFirstName.Text);
4) If the classes are in the same namespace, you can declare listbox as a global public property and access it from rest of the classes in the same namespace.
Does anyone know a way to open a 2nd form in a .NET application with a certain tab selected in a tab control on that form?
This is what my current code looks like which just opens the form:
SettingsForm TheSettingsForm = new SettingsForm(this);
TheSettingsForm.Show();
SettingsForm.cs is the name of the 2nd form to be opened.
Thanks in advance,
You just need to expose a property on your form that allows the calling code to set the desired tab. You might do it just by index like this:
var form = new SettingsForm(this);
form.SelectedTab = 2;
form.Show();
The property on the form would just set the appropriate property on the tab control:
public int SelectedTab
{
get { return _tabControl.SelectedIndex; }
set { _tabControl.SelectedIndex = value; }
}
Do something like this:
SettingsForm TheSettingsForm = new SettingsForm(this);
TheSettingsForm.TabPanel.SelectedIndex = SettingsFormTabIndexes.MyDesiredTab;
TheSettingsForm.Show();
where you've made a property in TheSettingsForm that exposes the tab control and SettingsFormTabIndexes is a friendly enum naming all the tabs by index.
Add an event handler to the TabControl.SelectedIndexChanged event.
myTabControl.SelectedIndexChanged += myTabControl_SelectedIndexChanged;
private void myTabControl_SelectedIndexChanged(object sender, EventArgs e) {
TabControl tc = sender as TabControl;
if (tc.SelectedIndex == indexOfTabToShowFormOn) {
TheSettingsForm.Show();
}
}