Best way to swap two .NET controls based on radio buttons - c#

I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user.
The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value.
This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?

Yep, that's pretty much how I do it. I would set the CheckedChanged event of both radio buttons to point at a single event handler and would place the following code to swap out the visible control.
private void OnRadioButtonCheckedChanged(object sender, EventArgs e)
{
Control1.Visible = RadioButton1.Checked;
Control2.Visible = RadioButton2.Checked;
}

Well you could also use databinding... seems a bit more elegant to me. Suppose you have two radiobuttons "rbA" and "rbB" and two textboxes "txtA" and "txtB". And you want to have txtA visible only when rbA is checked and txtB visible only when rbB is checked. You could do it like so :
private void Form1_Load(object sender, EventArgs e)
{
txtA.DataBindings.Add("Visible", rbA, "Checked");
txtB.DataBindings.Add("Visible", rbB, "Checked");
}
However... I observed that using UserControls instead of TextBoxes breaks the functionality and I should go read on the net why..
LATER EDIT :
The databinding works two-ways! : If you programatically set (from somewhere else) the visibility of the txtA to false the rbA will become unchecked. That's the beauty of Databinding.

Related

Enable/disable ui element usercontrol in wpf c# code behind

For a project, I create a Numpad and a keyboard.
Both are user controls and they are shown in a Window.
I want to use a button/toggle in xaml to enable the one or the other.
What is the best way to approach this in code- behind C#?
Thank you in advance!
Make a Button on the GUI and bind the Click event to a EventHandler in the Code Behind. This EventHandler basically just flip-flops the IsEnabled Property of the control Elements. Here is how something like this could look
private void BtnToggle_Click(object sender, RoutedEventArgs e)
{
//Do this with every button
BtnToFlip.IsEnabled = !Btn.ToFlip.IsEnabled
}
This flip-flops between IsEnabled from true to false
Note: This is in no way shape or form the best way to do this, and I am aware this is not even remotely MVVM. This is just a simple answer to OP's question as he seems to be very new.

how to unfocus datagridview in winform

I have some buttons, one textbox and a datagridview on a winform.
and i want when form show in the screen to put cursor on the textblock,
for this i use txtName.Focus().
But everytime when the from loads textbox doesn't focus,
indeed dagaridview takes a focus on itself.
how to solve it.
You should set the TabIndex property of the controls in your form (your TextBox for example should have the lowest TabIndex so that when the form loads it will automatically have focus )
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.TabStop = false;
textBox1.TabIndex = 0;
}
hope its help
Simply change the tabindex property of your controls.
Pay attention to use directly the tabindex property, because, if you have controls contained in other controls (groupbox or panels) it could be misleading.
Use the menu View and the TabOrder tool.
Put your textbox first in the taborder. No need to code anything
You have to make sure that the page has been loaded before giving the textbox focus. Therefore, add an event for the Form's Load event.
You can do this on the designer, or in the code behind like so:
this.Load += new EventHandler(Form1_Load);
During the loading event, call Select on your textbox.
private void Form1_Load(object sender, EventArgs e){
txt_Name.Select();
}
The Select command can choose how much of the text you select. For example, select the first letter starting a index 0 would be txt_Name.Select(0,0). More info at the
MSDN.
Alternatively, you can use the tabindex property to 0 to ensure it gets focus first (as per ionden).

Tab Control Shares The same buttons Winform

I wonder If it is possible to have fixed number of buttons that is shared by different tab pages. However I don't know how to implement this. Do you guys have any idea.
Heres a screenshot of my gui so that all of you can have a clearer view of what I meant.
I want that that the list of Customers, Reservations, and Check In/out will share the buttons search, edit, delete and refresh.
Is it possible? or should I create diff buttons for every tabpage?
is it correct if i do:
private void buttonSearch_Click(object sender, EventArgs e)
{
if(tabpage.SelectedIndex == 1){ then perform action..}
if(tabpage.SelectedIndex == 2) {then perform action...}
}
You could put the buttons in a User Control, add some events to the User Control (e.g. SearchClicked, EditClicked, etc.). Put the user control outside of the tabcontrol.
Then when you change tabs (TabIndexChanged), remove event handlers from the previous tab, and add event handlers for the new tab:
private void tabControl_TabIndexChanged(object sender, EventArgs e)
{
UserControl1.EditClicked -= OldEventHandler;
UserControl1.EditClicked += NewEventHandler;
}
Yes, you can change the .Parent property of the buttons at runtime - but wouldn't it be better to just move the buttons outside the tab control?
I feel you should create different buttons for every tab page as each one operates on a different entity. If there is only one set of buttons then you will have to first check which tab page is selected and then do the operation. So you will have one big method doing lots of things.
Plus there would be extra UI code that you will have to write to move the buttons when a tab page is selected.
With different buttons you will have highly cohesive and loosely coupled code. Better design. More maintainable and manageable. Less code.

combobox in C# not getting populated

I have a windows forms app in C#. Platform is vS 2005.
Following is the piece of code:
namespace HostApp
{
public partial class Form1 : Form
{
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.Items.Add("Apples");
comboBox2.Items.Add("Oranges");
comboBox2.Items.Add("Grapefruits");
}
}
}
I run the app but the fruit names do not show up in the drop down of comboBox2. I am sure I am missing some line of code to "populate" the drop down with the entered values.
Any help would be much appreciated.
Thanks,
Viren
You add the items in the handler for the SelectedIndexChanged event. You need to move the code to InitializeComponent or another appropriate place.
Please check the following things:
You have added AutoPostBack="true" in the combo-box so that the selectedChange event is fired and post back happens.
Make sure you have nothung in ur Page load which refreshed the combo box. You can use IsPostBack to acheive loading of the values.
Your items are being added when the selected item is changed, but as there are no existing items this will never happen. Move those lines to the constructor for Form1 and it'll work.
The code you provided will only add items to comboBox2 when the selection changes in the control that is hooked up to comboBox2_SelectedIndexChanged.
There are two concepts at play here: Control Initialization/Databinding, and event handling.
The code you have written essentially says "If somebody selects something new in the combo box, add these 3 options to the combo box". That would happen every time the selected index changes in the combo box. This, of course, assumes you have even hooked up this event handler to the combo box to begin with. This is event handling.
What you are probably trying to do is initialize the control. This happens when you load the page and want to setup the initial options available in your page controls. Using the Init or Load event is probably where you want to setup the choices in your control. This is also when you would initialize your event handlers to say "When something happens, do this".
Move the code to the Page_Load event ...
The SelectedIndexChanged only fires when the ComboBox index has changed AND AutoPostBack = True.
EDIT: Sorry, it's a Form, I was thinking web ... move to Form_Load
For people having difficulties with autopostback and viewstate, beware of the page_load event.
If have been getting on this page alot when trying to google, so that's the reason i'll post it here.
If you fill your dropdownlist (or any other control) in the page_load method, be sure to write an extra control is there is a postback (triggered when changing value of a dropdownlist).
If you don't make that control, your controls will be refilled.
That mistake took me a while to figure out.
So what i'm saying is
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill your controls here
}
}

DropDownList.SelectedValue changes (as a child control in a FormView) aren't sticking

Okay, I have a FormView with a couple of child controls in an InsertItemTemplate. One of them is a DropDownList, called DdlAssigned. I reference it in the Page's OnLoad method like so:
protected void Page_Load(object sender, EventArgs e)
{
((DropDownList)FrmAdd.FindControl("DdlAssigned")).SelectedValue =
((Guid)Membership.GetUser().ProviderUserKey).ToString();
}
Basically I'm just setting the default value of the DropDownList to the user currently logged in.
Anyway, when the page finishes loading the SelectedValue change isn't reflected on the page. I stepped through OnLoad and I can see the change reflected in my Watch list, but when all is said and done nothing's different on the page.
I figured it out. I'm still missing exactly why it doesn't work just on FormLoad, but performing the change in the FormView's DataBound event does the trick.
protected void FrmAdd_DataBound(object sender, EventArgs e)
{
// This is the same code as before, but done in the FormView's DataBound event.
((DropDownList)FrmAdd.Row.FindControl("DdlAssigned")).SelectedValue =
((Guid)Membership.GetUser().ProviderUserKey).ToString();
}
So, I guess the general rule of thumb is that if you are having problems making changes to controls when working with databinding, try to make them immediately after it has been bound.
I had a problem with dropdownlists and making the first value say something like, "Please select a value..." but without making it an actual selectable item, nor show up on the dropdownlist. I was binding the ddl in the page_load and I have to make sure that I set the text of the dropdownlist, AFTER it's been bound with data. You've accomplished the same thing by adding it to your databound section.

Categories