I have quite a few radiobuttonLists in my ASP.net webform. I am dynamically binding them using the method shown below:
public static void PopulateRadioButtonList(DataTable currentDt, RadioButtonList currentRadioButtonList, string strTxtField, string txtValueField,
string txtDisplay)
{
currentRadioButtonList.Items.Clear();
ListItem item = new ListItem();
currentRadioButtonList.Items.Add(item);
if (currentDt.Rows.Count > 0)
{
currentRadioButtonList.DataSource = currentDt;
currentRadioButtonList.DataTextField = strTxtField;
currentRadioButtonList.DataValueField = txtValueField;
currentRadioButtonList.DataBind();
}
else
{
currentRadioButtonList.Items.Clear();
}
}
Now, I want to Display only the first Letter of the DataTextField for the RadioButton Item Text.
For example if the Value is Good I just want to Display G. If it Fair I want to display F.
How do I do this in C#
Thanks
You can't do what you want when you do the binding, so you have 2 options:
Modify the data you get from the table, before you do the binding.
After binding, go through each item and modify its Text field.
So, it you want to display "only the first Letter of the DataTextField for the RadioButton Item Text", you can do:
currentRadioButtonList.DataSource = currentDt;
currentRadioButtonList.DataTextField = strTxtField;
currentRadioButtonList.DataValueField = txtValueField;
currentRadioButtonList.DataBind();
foreach (ListItem item in currentRadioButtonList.Items)
item.Text = item.Text.Substring(0, 1);
If I misunderstood you and you want to display the first letter of the Value field, you can replace the last two lines with:
foreach (ListItem item in currentRadioButtonList.Items)
item.Text = item.Value.Substring(0, 1);
You could add a property to the type that is being bound (the one that contains Good, Fair, etc.) and bind to this property. If you will always be using the first letter, you could make it like so (adding in null checks, of course):
public string MyVar { get; set; }
public string MyVarFirstChar
{
get { return MyVar.Substring(0, 2); }
}
Related
I have one combobox in which I have set DataSource Value, but when I try to set SelectedValue, the ComboBox returns null. so please help.
BindingList<KeyValuePair<string, int>> m_items =
new BindingList<KeyValuePair<string, int>>();
for (int i = 2; i <= 12; i++)
m_items.Add(new KeyValuePair<string, int>(i.ToString(), i));
ComboBox cboGridSize = new ComboBox();
cboGridSize.DisplayMember = "Key";
cboGridSize.ValueMember = "Value";
cboGridSize.DataSource = m_items;
cboGridSize.SelectedValue = 4;
when I set SelectedValue with 4 then it returns NULL.
Agree with #Laazo change to string.
cboGridSize.SelectedValue = "4";
or somthing similar to this
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());
and refer to this looks as if it would be good for your issue:
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem(v=vs.110).aspx
How do I set the selected item in a comboBox to match my string using C#?
Getting selected value of a combobox
I came across this question while also trying to solve this problem. I solved it by creating the following extension method.
public static void ChooseItem<T>(this ComboBox cb, int id) where T : IDatabaseTableClass
{
// In order for this to work, the item you are searching for must implement IDatabaseTableClass so that this method knows for sure
// that there will be an ID for the comparison.
/* Enumerating over the combo box items is the only way to set the selected item.
* We loop over the items until we find the item that matches. If we find a match,
* we use the matched item's index to select the same item from the combo box.*/
foreach (T item in cb.Items)
{
if (item.ID == id)
{
cb.SelectedIndex = cb.Items.IndexOf(item);
}
}
}
I also created an interface called IDatabaseTableClass (probably not the best name). This interface has one property, int ID { get; set; } To ensure that we actually have an ID to compare to the int id from the parameter.
Great website - very helpful in my C# Class.
I am trying to write a method in C# that will Check fields for null entry and change field background to LightYellow?
The form is a display form that views records in a SQL database.
Here is what I tried - but the variable for the field names isn't translating to the field name.
Advice?
// YellowBack Method fills background of key fields that are missing data or are NULL
private void YellowBack()
{
//Bool fieldContents = true;
string fieldVariable;
string[] fieldName = { "activity_TitleTextBox", "act_Title2TextBox", "kid_NotesTextBox", "review_AdultTextBox",
"phoneTextBox", "addressTextBox", "cityTextBox", "websiteTextBox", "weblink_TextTextBox",
"hoursTextBox", "admissionTextBox" };
int count = 0;
//Check each field name
for (int index = 0; index < fieldName.Length; index++)
{
fieldVariable == fieldName.Text;
if (fieldVariable.Trim = "")
{
fieldVariable.BackColor = LightYellow;
}
else
{
fieldVariable.BackColor = Window;
}
}
}
You are not using the index . . . . you should be using something like:
fieldVariable = fieldName[i].Text;
I also think that you won't be able to set the property BackColor on fieldVariable as it is a string. You should probably be using the object grid or text control that your database binds to and setting the color properties of that . . . but I'm not sure there's enough information here to go on.
I think the problem is that you're looping through a list of strings and trying to make the string into a TextBox control. Instead, you should probably loop through all the controls on the form, and for each one that is a TextBox, see if it's name matches a name in your list. Then you can set the back color of the control based on the Text property.
There are other problems with your code also, like in your if statement you are doing an assignment (=) instead of a comparison (==).
Here's what I would do:
private void HighlightEmptyFields()
{
// Create a list of all the text box names that we want to examine
var textBoxNames = new List<string>
{
"activity_TitleTextBox", "act_Title2TextBox", "kid_NotesTextBox",
"review_AdultTextBox", "phoneTextBox", "addressTextBox", "cityTextBox",
"websiteTextBox", "weblink_TextTextBox", "hoursTextBox", "admissionTextBox"
};
// Loop through every control on the form
foreach (Control formControl in this.Controls)
{
// Find the groupbox control by name
if (formControl.Name != "groupBox1") continue;
// We found the group box, so loop through every control in it
foreach (Control groupBoxControl in formControl.Controls)
{
// Try to cast the control to a TextBox.
var textBoxControl = groupBoxControl as TextBox;
// If the cast fails, move on to the next one...
if (textBoxControl == null) continue;
// Now we have one a textbox control, so see if the
// textBoxNames array contains the name of this text box.
if (textBoxNames.Contains(textBoxControl.Name,
StringComparer.OrdinalIgnoreCase))
{
// We found a match, so set the backcolor based on Text property
if (textBoxControl.Text.Trim() == "")
{
textBoxControl.BackColor = Color.LightYellow;
}
else
{
textBoxControl.BackColor = Color.White;
}
}
}
// Since we found the control we were looking for, we can stop looking
break;
}
}
I need to display values like "Surreptitiously" and "Discreetly" in a comboBox but thereafter be able to set the comboboxes' SelectedItem based on the underlying DB values for those words (e.g., "S" and "D").
I reckon I can use the comboBoxes' DisplayMember and ValueMember properties for this somehow, but can I subsequently do something analagous to the following with the actual (valuemember) values:
comboBoxAdverbs.SelectedIndex = comboBoxAdverbs.Items.IndexOf(weirdAdverbs[CURRENT_ADVERB]);
As "weirdAdverbs[CURRENT_ADVERB]" contains the values like "S" and "D" it, of course, doesn't find and set the SelectedIndex when the comboBox contains the values "Surreptitiously" and "Discreetly"
If I set the combobox Item Tag value to "S" and "D" (assuming that's possible), I can loop through those values, but I'm hoping there's a one-line way of doing it similar to the "IndexOf()" above.
I use a template class for this and it comes in pretty darn handy. The combo box will show whatever text you want and you can store a value with it.
public class cboItem<T>
{
public cboItem(string name, T value)
{
this.Name = name;
this.Value = value;
}
public string Name { get; set; }
public T Value { get; set; }
public override string ToString()
{
return Name == null ? "" : Name;
}
}
Combo box items can be anything, including classes/structs. By default it will use the ToString() implementation to display items, but if you populate a set of objects you can use DisplayMember and ValueMember to great effect.
As a simple example to give you some ideas we'll bind the combo box to a set of KeyValuePair instances for your weird verb codes and their descriptive names. Alternatively you can use linq to compose anonymous types, or create your own suitable classes/structs.
private void populateCombo()
{
comboBoxAdverbs.Items.Clear();
comboBoxAdverbs.Items.Add( new Tuple<string, string>( "S", "Surreptitiously" ) );
comboBoxAdverbs.Items.Add( new Tuple<string, string>( "D", "Discreetly" ) );
comboBoxAdverbs.DisplayMember = "Item2";
}
Then in your code where you want to select an item matching a provided code: (I.e. "D")
var item = comboBoxAdverbs.Items
.OfType<Tuple<string,string>>()
.FirstOrDefault(i => string.Compare(i.Item1, textBox1.Text, true) == 0);
if (item != null)
comboBoxAdverbs.SelectedItem = item;
This attempts to find the matching item by comparing the key against whatever input (in this case a textbox value) and if it finds a match, sets the SelectedItem to tell the combo box to select it.
** Edit: Whups, had originally use KeyValuePair which I didn't realize was a struct so no Null check-ability. Changed to Tuple (Essentially Pair)
What I found that works for me is to store the selectedindex value, after it's set, into the combobox's Tag property. Then, if the user attempts to change the selectedIndex when it is supposed to be in a "readonly" state, simply change it back to the selectedIndex value stored in the Tag property:
comboBoxPlatypusId.SelectedIndex = comboBoxPlatypusId.Items.IndexOf(DuckbillVals[Duckbill_PlatypusID]);
comboBoxPlatypusId.Tag = comboBoxPlatypusId.SelectedIndex;
...
private void comboBoxFunnyMammals_SelectedValueChanged(object sender, EventArgs e) {
var cb = sender as ComboBox;
if (cb != null)
{
int validSelection = Convert.ToInt32(cb.Tag);
if (cb.SelectedIndex != validSelection) {
cb.SelectedIndex = validSelection;
}
}
}
I have user submitted content that is loaded into c# winform in our office for processing before officially added to database. The user can submit a 'Referrer' as two text fields-first and last name. In the office I want to have a combobox will all existing referrers loaded in, then the first couple letters of the name to advance the combobox down to the area it needs to be at. I want to do something like this, taking the first two letters of the name and use that to initialize the combobox.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = "" + txtrefFirstName.Text[0] + txtrefFirstName.Text[1];
firstStart = firstStart.ToUpper();
ddlReferring.SelectedText.StartsWith(firstStart);
}
else
ddlReferring.Text = "";
Any ideas or suggestions to get this to work?
Thanks
David K.
You could write something like this...
foreach (string item in ddlReferring.Items)
{
if (item.StartsWith(firstStart))
{
ddlReferring.SelectedText = item;
break;
}
}
Assuming the ddl's datasource is a List of String objects, you should be able to do some comparison on the datasource itself. I tend to use Linq for things like this but it isn't strictly necessary, just shorter.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = txtrefFirstName.Text.Substring(0,2).ToUpper();
string Selection = ddlReferring.DataSource.Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
ddlReferring.SelectedText = Selection ?? "";
}
else
ddlReferring.Text = "";
The selection line can also come from the items collection directly
string Selection = ddlReferring.Items.OfType<string>().Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
Or if you REALLY dont want to use Linq...
string Selection = "";
foreach (object item in ddlReferring.Items)
if (item.ToString().StartsWith(firstStart))
{
Selection = item.ToString();
break;
}
Similar methods can be used even if the ddl's data is not a list of strings, just make sure to cast the items appropriately and compare the correct values.
A few days ago, I wrote about issues with implementing a ListView in ASP.NET. Now, with all of the other code written, I'm having trouble saving changed items in a ListView.
A few things of note:
The Save button is not part of the ListView proper; it calls the GetListViewItems() method, which in turns call the Save() method.
The Listview.DataBind() event is invoked when a button is pressed requesting the records to be updated
The Listview shows text using <%#Eval("Key.Name") %> and a named DropDownList using <%#Eval("Value") %>
Getting The Items From the ListView
public void GetListViewItems()
{
List<Foo> Result = FooManager.CreateFooList();
DropDownList ddl = null;
ListViewItem Item = null;
try
{
foreach (ListViewDataItem item in lvFooList.Items)
{
Item = item;
ddl = ((DropDownList) (Item.FindControl("ddlListOfBars")));
if (//something is there)
{
Foo foo = FooManager.CreateFoo();
foo.Id = item.DataItemIndex; //shows null
int barId = int.Parse(ddl.SelectedItem.Value); //works just fine
foo.barId = barId;
Result.Add(foo);
}
}
}
catch (Exception ex)
{
//Irrelevant for our purposes
}
}
DataBinding the ListView
The code to databind the ListView is shown here in my previous question.
Question(s):
Why is it that when I iterate through the ListViewDataItem in the Listview that each item is null?
How can I retrieve the Foo.Id from the Dictionary?
What else might I be missing?
What would I use if I wanted to get that Id Programmatically based on what items were shown? As it is now, the current ListView is shown based on what Foos were selected. Those Foos selected are then displayed, and the user can change the Bar in the DropDownList, hit Save, and those changes are propogated.
Update
As it turns out, my problem was what leppie had said; and that was that I needed to specify DataKeyNames and use those to retain the information from the ListView.
Here's the code I added:
try
{
int DataKeyArrayIndex = 0;
foreach (ListViewDataItem item in lvFooList.Items)
{
Item = item;
ddl = ((DropDownList) (Item.FindControl("ddlListOfBars")));
if (//something is there)
{
Foo foo = FooManager.CreateFoo();
Foo tempFoo = FooManager.CreateFoo();
if (lvFooList != null)
{
tempFoo = ((Foo)(lvFooList.DataKeys[DataKeyArrayIndex].Value));
}
foo.Id = tempFoo.Id;
int barId = int.Parse(ddl.SelectedItem.Value); //works just fine
foo.barId = barId;
Result.Add(foo);
DataKeyArrayIndex++;
}
}
}
And then in the .ascx file, I added DataKeyNames="Key", like so:
<asp:ListView ID="lvFooList" runat="server" DataKeyNames="Key">
This allowed me to use the Key from my previous post to determine which Foo was being looked at.
Any critiques of this approach, as well as methods for making it better are greatly appreciated.
Some quick answers:
Your need to use databinding for that to work, in other words, assign to DataSource and call DataBind(). EDIT: seems you are doing that. But remember it wont persist between postbacks, just the DataKey (see below).
If I recall correctly, you need to specify the DataKeyNames, and they can be retrieved from the DataKey property then.
you can also use the ListViewDataItem.DataItemIndex property instead of keeping your own index, as in:
foreach (ListViewDataItem item in MyListView.Items)
{
// in this example key is a string value
Foo foo = new Foo(MyListView.DataKeys[item.DataItemIndex].Value as string);
// do stuff with foo
}