Dropdownlist text change while hidden aspx - c#

I have a drop down list with autopostback enabled. When I change the value it updates a grideview on my webpage. However I want to get rid of the drop down and use a textbox sort of like a search function. I still want to keep my list though so I can compare my search string to the actual present values. However, if I make my dropdown list invisible I cant compare values to the items in it.
Or is there a better solution? A control that the user can't see but that I can put database values in it and compare those values with textbox text?
thanks for the help.
I am getting an error with this code:
foreach (string s in DropDownList3.Items)
{
//foreach gives me the error below
if(s == idsearch.Text)
{
valid = true;
break;
}
}
if(valid == true)
{
GridView1.DataBind();
}

DropDownList3.Items return a System.Web.UI.WebControls.ListItem and not List. You should do this
foreach (ListItem item in DropDownList3.Items)
{ //foreach gives me the error below
if(item.Text == idsearch.Text)
{
valid = true;
break;
}
}

error is due to casting ListItem to string. Do as :
foreach (ListItem s in DropDownList3.Items)
{
if(s.Text== idsearch.Text){
valid = true;
break;
}
}
Or you can find item by Text or Value using DropDownList.Items.FindByText or DropDownList.Items.FindByValue methods.
var searchResult = DropDownList1.Items.FindByText(idsearch.Text);
bool valid = searchResult != null;

Why not just use a variable in your server side code to store the values in the dropdownlist. So for example..
String [] comparedValues = new String[4] {"value1", "value2", "value3", "value4"};
and then..
if (comparedValues.Contains(myTextBox.Text))
{
// Do Something...
}

Related

C# Search item and return in Listview

I have some question about Listview in C#
My listview contains with 2 column like this :
colDATA1 colDATA2
Value1 Amount1
Value2 Amount2
Value3 Amount3
Value4 Amount4
And what I am trying to make is search Amount5 in Listview If not exist then do something.And if exist then return the Value5
I am trying to search and use the code like this :
If (Listview1.items.containskey("Amount5"))
{}
else
{MessageBox.show("Not Found")}
or if exist then return the value5 *I have no idea how to do.
I am searching this in google but most of it have only 1 Column and when I use the code the code won't work.
My question is :
1. How can I get Value5 if Amount5 exist.
Thank you.
The code to add the items
First Set listView1 Property "View : Details" Then Using this code
this.Listview1.Items.Add(new ListViewItem(new string[] { Value1, Amount1 }));
The OP already figured it out but this is just for future reference in case someone needs it.
What OP was missing is that ListView holds its items as objects in the Items property.
If (Listview1.items.containskey("Amount5"))
{}
else
{MessageBox.show("Not Found")}
containsKey is usually in dictionaries-like data structures. However, a ListView controller's Items is ItemCollection (for dictionaries you can use a DataGrid)
In your case I would do this using Linq.
// Returns the first item that satisfies the condition or null if none does.
ListViewItem found = items.FirstOrDefault(i => i.SubItems[1].Text.Equals("Amount5"));
if(found != null) {
MessageBox.Show(found.SubItems[0].Text.ToString());
}
else {
MessageBox.Show("Not Found!");
}
You can still use a for loop to do the same thing too.
If I want to use a foreach loop (since Linq can't be directly used on ListView.Item)
ListViewItem found = null;
foreach (ListViewItem item in listView1.Items) {
if (item.SubItems[1].Text.Equals("Amount5")) {
// If a match was found break the loop.
found = item;
break;
}
}
if (found != null) {
MessageBox.Show(found.SubItems[0].Text.ToString());
}
else {
MessageBox.Show("Not Found!");
}
Hope this helps!

Check fields for null entry and change field background to lightyellow?

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;
}
}

set combobox text from textbox

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.

how to set the default value to the drop down list control?

I have a drop down list control on my web page. I have bind the datatable to the dropdownlist control as follows -
lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
in the page load event i want to set the default value to the drop down list control from my other table field.
how to do this?
After your DataBind():
lstDepartment.SelectedIndex = 0; //first item
or
lstDepartment.SelectedValue = "Yourvalue"
or
//add error checking, just an example, FindByValue may return null
lstDepartment.Items.FindByValue("Yourvalue").Selected = true;
or
//add error checking, just an example, FindByText may return null
lstDepartment.Items.FindByText("Yourvalue").Selected = true;
if you know the index of the item of default value,just
lstDepartment.SelectedIndex = 1;//the second item
or if you know the value you want to set, just
lstDepartment.SelectedValue = "the value you want to set";
Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:
lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items)
{
if (item.Value == otherDropDownList.SelectedValue)
{
item.Selected = true;
}
}
lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
'Set the initial value:
lstDepartment.SelectedValue = depID;
lstDepartment.Attributes.Remove("InitialValue");
lstDepartment.Attributes.Add("InitialValue", depID);
And in your cancel method:
lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");
And in your update method:
lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;

Populating RadiobuttonList dynamically

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); }
}

Categories

Resources