Radiobuttons, how to replace all those if statements - c#

Several places in my program, the RadioButton matching the selected item has to be checked, and I have a lot of if statements like so:
DataRowView TempRow = (DataRowView)ScheduleDataGrid.SelectedItem;
if (Convert.ToString(TempRow["Bio"]) == "Bio1")
{
BioRB1.IsChecked = true;
}
if (Convert.ToString(TempRow["Bio"]) == "Bio2")
{
BioRB2.IsChecked = true;
}
if (Convert.ToString(TempRow["Bio"]) == "Bio3")
and so on... I want to replace all this with something short and smart.
I tried using the number of the bio to relate to the button like so:
string bioselected = Convert.ToString(TempRow["Bio"]);
int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1));
BioRB[i].IsChecked = true;
but doing a BioRB[i] doesn't work, it ignores the [i] and says BioRB does not exist. Any other suggestions?

BioRB[i] is not doing anything like what you think it's doing. All variable references (controls included) have to be well-defined at compile time - you can't refer to a control's name by building a string that matches the name.**
Try creating a list of your radio buttons. Then you can index into the list:
List<RadioButton> radioButtons = new List<RadioButton>()
{
BioRB1,
BioRB2
};
string bioselected = Convert.ToString(TempRow["Bio"]);
int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1));
radioButtons[i].IsChecked = true;
** Technically you can do this via reflection, but it's far more complex than what you've tried.

Maybe this will look better:
string caseSwitch = Convert.ToString(TempRow["Bio"]);
switch (caseSwitch)
{
case "Bio1":
BioRB1.IsChecked = true;
break;
case "Bio2":
BioRB2.IsChecked = true;
break;
case "Bio3":
BioRB3.IsChecked = true;
break;
default:
Console.WriteLine("Default case...is optional");
break;
}
Also, try doing what Alybaba726 said and use CellContentClick or something like this:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if(e.ColumnIndex == dgv.Columns["Bio"].Index)
{
string bioSelected = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
switch (bioSelected)
{
case "Bio1":
BioRB1.IsChecked = true;
break;
case "Bio2":
BioRB2.IsChecked = true;
break;
case "Bio3":
BioRB3.IsChecked = true;
break;
default:
Console.WriteLine("Default case...this is optional");
break;
}
}
}

Related

Input string was not in a correct format - trying to insert string value to int typed datagridview cell

I'm trying to fill in a telerik radDataGridView (the same problem happens with a normal dataGridView as well).
one of the columns in my db table is named [updateType].
the 'type' is described in an enum:
public enum TypeEnum
{
INSERT = 0,
UPDATE_OR_INSERT = 1,
UPDATE = 2,
DELETE_OR_INSERT = 3
};
i'm filling the dataGridView (dgv) in the Load event:
private void Form1_Load(object sender, EventArgs e)
{
this.table1TableAdapter.Fill(this.tempdbDataSet.Table1);
for (int i = 0; i < dgv.RowCount; i++)
{
switch ((int)dgv.Rows[i].Cells[2].Value)
{
case (int)TypeEnum.INSERT:
dgv.Rows[i].Cells[2].Value = "INSERT";
break;
case (int)TypeEnum.UPDATE_OR_INSERT:
dgv.Rows[i].Cells[2].Value = "UPDATE/INSERT";
break;
case (int)TypeEnum.UPDATE:
dgv.Rows[i].Cells[2].Value = "UPDATE";
break;
case (int)TypeEnum.DELETE_OR_INSERT:
dgv.Rows[i].Cells[2].Value = "INSERT/DELETE";
break;
default:
break;
}
}
}
but it fails, when trying to fill in a string value to an int typed gridview cell,
throwing an exception Input string was not in a correct format.
thanks to anyone who can solve this.
Try
switch ((int)dgv.Rows[i].Cells[2].Value)
{
case (int)TableUpdateModeEnum.INSERT:
dgv.Rows[i].Cells[2].Value = (int)TypeEnum.INSERT;
break;
...
...
}
I've solved my problem in a different way.
instead of filling the datagridview with a table adapter,
i've built it step by step.
for example:
//---
for (int i = 0; i < dataset.Tables[0].Rows.Count; i++)
dgv.Rows.Add(dataset.Tables[0].Rows[i].ItemArray[0].ToString(),
dataset.Tables[0].Rows[i].ItemArray[1].ToString(),
GetEnumString((int)dataset.Tables[0].Rows[i].ItemArray[2]));
//---
private string GetEnumString(int n)
{
switch (n)
{
case (int)TypeEnum.INSERT:
return "INSERT";
case (int)TypeEnum.UPDATE:
return "UPDATE";
case (int)TypeEnum.UPDATE_OR_INSERT:
return "UPDATE/INSERT";
case (int)TypeEnum.DELETE_OR_INSERT:
return "INSERT/DELETE";
default: return "";
}
}
}
public enum TableUpdateModeEnum
{
INSERT = 0,
UPDATE_OR_INSERT = 1,
UPDATE = 2,
DELETE_OR_INSERT = 3
};
thank you anyway!

How to convert radio button list value to bit in asp.net

This is code for inserting value to database but Radio button list value is not converted and inserting failed.
using (SathsurEntities se = new SathsurEntities())
{
tbl_Events user = new tbl_Events();
user.Event_name = txtEventName.Text;
user.Event_date = Convert.ToDateTime(txtEventDate.Text);
user.Image_url = lblimg.Text;
user.Is_free_entry = Convert.ToBoolean(rblEntry.SelectedValue);
user.Booking_url = txtBooking.Text;
se.AddTotbl_Events(user);
se.SaveChanges();
Response.Write("Event Added Successfuly!");
}
a simple answer,
private bool value=true;
if (rblEntry.SelectedValue == "1")
{
value = true;
}
else if (rblEntry.SelectedValue == "2")
{
value = false;
}
user.Is_free_entry = value;
user.Is_free_entry = rblEntry.SelectedValue == "1";
OR
user.Is_free_entry = rblEntry.SelectedValue != "2";
If you can guarantee that all you ever get is either 1 or 2, then these are identical. If you want to try and catch other values, then the first (== "1") emphasizes that you ONLY get true when the value is 1 and you get false for all other values. The second (== "2") says you ONLY get false if the value is 2 and you get true for all other values. Thus, you can set a default on what to do if you get odd values. If you want to detect odd values and throw an exception or do other error handling, then you'll want to go with Vikas Rana's suggestion, but with an additional else
If you are only want to have two value , should have 'true' and 'false', it's enough .
if you have more value or more type ,you can use the type of byte or int ....
the you should use the if ... else ... or switch ... case ...
<asp:RadioButtonList ID="rblList" runat="server">
<asp:ListItem Text="True" Value="True" Selected="True"></asp:ListItem>
<asp:ListItem Text="False" Value="False"></asp:ListItem>
</asp:RadioButtonList>
var a = Convert.ToBoolean(rblList.SelectedValue);
or
var a = Convert.ToInt16(rblList.SelectedValue);
var retValue = string.Empty;
switch (a)
{
case 0:
//"you want have"
break;
case 1:
//"you want have"
break;
case 2:
//"you want have"
break;
default:
//"you want have"
break;
}
or
if (a == 0)
{
//"you want have"
}
else if (a == 1)
{
//"you want have"
}
else if (a == 2)
{
//"you want have"
}
else
{
//"you want have"
}
this is where you might use an extension method along the lines of this:
public static class BooleanExtensions
{
public static bool ToBool(this string value)
{
bool result = false;
switch (value.ToLower().Trim())
{
case "y":
case "yes":
case "1":
result = true;
break;
case "n":
case "no":
case "0":
result = false;
break;
}
return result;
}
}
usage:
var value="0";
Console.Write(value.ToBool());
Should output false.
to use in your project, include that class above. You would use this in your code example like so
using (SathsurEntities se = new SathsurEntities())
{
tbl_Events user = new tbl_Events();
user.Event_name = txtEventName.Text;
user.Event_date = Convert.ToDateTime(txtEventDate.Text);
user.Image_url = lblimg.Text;
user.Is_free_entry = rblEntry.SelectedValue.ToBoolean();
user.Booking_url = txtBooking.Text;
se.AddTotbl_Events(user);
se.SaveChanges();
Response.Write("Event Added Successfuly!");
}

Stackoverflow exception from updating combobox in winforms/C#

I'm geting a StackOverflowException. Somehow, posting here seemed appropriate.
I'm using Windows Forms in a C# application. This application is intended to run on Linux, FreeBSD and Mac-OS, so I can't use WPF, so please don't suggest it.
My guess is that I'm missing a nuance of WinForms, but I cant seem to figure out what.
The ComboBox is generated by the GUI form builder in VS 2010.
The specific lines of code that are throwing the error are here:
if(cur_num_is_valid)
{
cbx_material_num.Text = num;
}
else
{
num = "0";
//I only have one of the following two at a time. Both overflow
cbx_material_num.SelectedIndex = 0;
cbx_material_num.Text = "0";
}
Since the code is somewhat complex, here's the whole function code. 'cbx_' indicates a combo box. 'txtb_' is a text box.
private void cbx_material_numobj_SelectedIndexChanged(object sender, EventArgs e)
{
string obj = cbx_material_obj.Text;
string num = cbx_material_num.Text;
int selnum = 0;
int n = 0;
//do we need to recreate the numbers array?
bool cur_num_is_valid = false;
cbx_material_num.Items.Clear();
if(obj != lastobj)
{
n = m_demo.get_object_modifiers(obj);
for(int i = 0; i <= n; i++)
{
string s = i.ToString();
if(s == num && i < n) cur_num_is_valid = true;
cbx_material_num.Items.Add(s);
}
}
if(cur_num_is_valid)
{
cbx_material_num.Text = num;
}
else
{
num = "0";
//Overflow here:
cbx_material_num.SelectedIndex = 0;
}
try
{
selnum = int.Parse(num);
}
catch(Exception)
{
MessageBox.Show("Error, second select menu after 'object modifiers' must be a number, not '"+num+"'.");
cbx_material_num.Text="0";
return;
}
if(selnum >= n)
{
txtb_material_param1.Text = "0";
txtb_material_param2.Text = "0";
txtb_material_param3.Text = "0";
txtb_material_param4.Text = "0";
}
else
{
MaterialFace face;
MaterialParameter parameter;
int typeid;
object paramdata;
m_demo.get_object_modifiers_material(obj, selnum, out face, out parameter, out typeid, out paramdata);
cbx_material_face.Text = face.ToString();
cbx_material_paramtype.Text = parameter.ToString();
switch(typeid)
{
case 0:
txtb_material_param1.Text = ((float)paramdata).ToString();
cbx_material_datatype.Text = "float";
goto case -1;
case 1:
float[] parsf = ((float[])paramdata);
txtb_material_param1.Text = parsf[0].ToString();
txtb_material_param2.Text = parsf[1].ToString();
txtb_material_param3.Text = parsf[2].ToString();
txtb_material_param4.Text = parsf[3].ToString();
cbx_material_datatype.Text = "float[]";
break;
case 2:
txtb_material_param1.Text = ((int)paramdata).ToString();
cbx_material_datatype.Text = "int";
goto case -1;
case 3:
int[] parsi = ((int[])paramdata);
txtb_material_param1.Text = parsi[0].ToString();
txtb_material_param2.Text = parsi[1].ToString();
txtb_material_param3.Text = parsi[2].ToString();
txtb_material_param4.Text = parsi[3].ToString();
cbx_material_datatype.Text = "int[]";
break;
case -1: //can't actuall be returned, used to 'blank' the last three as '0'
txtb_material_param2.Text = "0";
txtb_material_param2.Text = "0";
txtb_material_param3.Text = "0";
break;
case 4:
OpenTK.Graphics.Color4 paramc = ((OpenTK.Graphics.Color4)paramdata);
txtb_material_param1.Text = paramc.R.ToString();
txtb_material_param2.Text = paramc.G.ToString();
txtb_material_param3.Text = paramc.B.ToString();
txtb_material_param4.Text = paramc.A.ToString();
cbx_material_datatype.Text = "Color4";
break;
default: //5
Vector4 paramv = ((Vector4)paramdata);
txtb_material_param1.Text = paramv.X.ToString();
txtb_material_param2.Text = paramv.Y.ToString();
txtb_material_param3.Text = paramv.Z.ToString();
txtb_material_param4.Text = paramv.W.ToString();
cbx_material_datatype.Text = "Vector4";
break;
}
}
}
You need to check that the SelectedIndex isn't already 0 before you try to set it:
if (cbx_material_num.SelectedIndex != 0){
cbx_material_num.SelectedIndex = 0;
}
Otherwise you're re-firing the event every time through.
I think that whenever you set this cbx_material_num.SelectedIndex = 0; within the EventHandler you invoke your
cbx_material_numobj_SelectedIndexChanged(object sender, EventArgs e)
Each call invokes another eventHandler so the stack fills up after some time.
Basically, the fact that it is called SelectedIndexChanged doesn't mean that the value has to be different from the previous one but that the value is set through its setter.

Hide password text

I have a textbox using UseSystemPasswordChar, so it will not display the password that the user enters. The issue is that the password is still able to be read by something like Spy++. I'm looking for a way to hide this like they do in the password fields in the Services.msc > Log On tab.
Here is what I've got so far.
You can improve this by having some unique events to indicate whether a pressed key has been accepted, if InputFilter or RealText has been changed, etc...
Another great thing to improve would be the default usage of InputFilter, because working with char and Keys doesn't really work for many special keys. For example - at the moment, if you press Alt+F4 when the PasswordBox is in focus, it will type in 's'... So there's a bag of bugs to fix.
And lastly, there's probably a more elegant way to handle capital vs non-capital letters input than what I did there.
So here it is:
public class PasswordBox : TextBox
{
private string _realText;
public string RealText
{
get { return this._realText; }
set
{
var i = this.SelectionStart;
this._realText = value ?? "";
this.Text = "";
this.Text = new string('*', this._realText.Length);
this.SelectionStart = i > this.Text.Length ? this.Text.Length : i;
}
}
private Func<KeyEventArgs, bool> _inputFilter;
public Func<KeyEventArgs, bool> InputFilter
{
get { return this._inputFilter; }
set { this._inputFilter = value ?? (e => true); }
}
public PasswordBox()
{
this.RealText = "";
this.InputFilter = e => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".Any(c => c == e.KeyValue);
}
protected override void OnKeyDown(KeyEventArgs e)
{
e.SuppressKeyPress = true;
switch (e.KeyCode)
{
case Keys.Back:
if (this.SelectionStart > 0 || this.SelectionLength > 0)
{
this.RealText = this.SelectionLength == 0
? this.RealText.Remove(--this.SelectionStart, 1)
: this.RealText.Remove(this.SelectionStart, this.SelectionLength);
}
break;
case Keys.Delete:
if (this.SelectionStart == this.TextLength)
{
return;
}
this.RealText = this.RealText.Remove(this.SelectionStart, this.SelectionLength == 0 ? 1 : this.SelectionLength);
break;
case Keys.X:
case Keys.C:
case Keys.V:
if (e.Control)
{
return;
}
goto default;
case Keys.Right:
case Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Shift:
case Keys.Home:
case Keys.End:
e.SuppressKeyPress = false;
base.OnKeyDown(e);
break;
default:
if (e.Control)
{
e.SuppressKeyPress = false;
base.OnKeyDown(e);
break;
}
if (this.InputFilter(e))
{
var c = (char)e.KeyValue;
if (e.Shift == IsKeyLocked(Keys.CapsLock))
{
c = char.ToLower(c);
}
this.RealText = this.RealText.Remove(this.SelectionStart, this.SelectionLength)
.Insert(this.SelectionStart, c.ToString());
this.SelectionStart++;
}
break;
}
}
}
So try something like this
private string realpass = "";
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (Char) Keys.Back)
realpass += realpass.Substring(0, realpass.Length - 2);
realpass += e.KeyChar.ToString();
textBox1.Text = "";
for (int i = 0; i < realpass.Length; i++)
textBox1.Text += "*";
}
You should not use your own dialog if you intend to collect Windows/domain user credentials. You should use what Windows provides via PInvoke or simply use a wrapper like this,
http://weblogs.asp.net/hernandl/archive/2005/11/21/usercredentialsdialog.aspx
and this,
http://credentials.codeplex.com/

C# datagridview Wrong column index

i've got an event handler for columncontentclicked and it works fine, until i shorten the datalist with stored procedure. after that the indexnum that is return is 0 instead of 5 or 6.
Do i have to refresh datagridview or something?
here's te code
:
int lastcol = dataGridView1.Columns.Count;
// MessageBox.Show(e.ColumnIndex.ToString() + lastcol.ToString());
if (e.ColumnIndex == lastcol - 1)
{
int index = int.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
Global.size = this.Size;
Global.position = this.Location;
Global.overzicht_select = index.ToString();
if (Global.give_return == false)
{
switch(type)
{
case 1:
Global.edit_form_proj = false;
project_form project_form1 = new project_form(this);
project_form1.Show(this);
this.Hide();
break;
case 2:
Global.edit_form_bedr = false;
bedrijf_form bedrijf_form1 = new bedrijf_form(this);
bedrijf_form1.Show(this);
this.Hide();
break;
case 3:
Global.edit_form_pers = false;
persoon_form persoon_form1 = new persoon_form(this);
persoon_form1.Show(this);
this.Hide();
break;
}
}
else
{
Global.return_id = index.ToString();
if (pf != null)
{
pf.fill_id();
}
if (pr != null)
{
pr.fill_id();
}
Global.give_return = false;
Close();
}
}
}
}
I found my problem. the column that I wanted clickable is a buttoncolumn, witch I add when loading the grid. but after filter that column doesnt get refresh or get new data so it things i is the first and only column left whilst the other columns get rebuilt. so calling dataGridView1.Columns.Clear(); and recreating the button column after grid is refilld did the trick, –

Categories

Resources