dropdownlist always show the first index of Item populated from database and in debug mode ddlcountry.Text always empty string("").
I have "Philippines" item in my dropdownlist but "Argentina" always shown first in my dropdown instead of "Philippines".
Please help.
//in formload
if(!isPostback)
{
DataTable dtCountry= new DataTable();
dtCountry= network.GetCountry();
for (int row = 0; row < dtCountry.Rows.Count; row++)
{
ddlCoutry.Items.Add(new ListItem { Text = dtCountry.Rows[row][1].ToString(), Value = dtCountry.Rows[row][1].ToString() });
}
}
ddlCountry.Text = "Philippines";
As I mentioned in the comment above, I think your problem is you are trying to select the dropdown option by text but getting confused with .Text property. You can do this:-
ddlCountries.Items.FindByText("Philippines").Selected = true;
Set the selected item to "Philippines" because I assume your list of countries is in alphabetical order.
ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText("Philippines"));
Also I want to point out your variable is misspelled:
**ddlCoutry**.Items.Add(new ListItem { Text = dtCountry.Rows[row][1].ToString(), Value = dtCountry.Rows[row][1].ToString() });
Related
When I was working on one of my projects I was trying to write to a datasourced combobox and then write a value into the combobox like below:
//Create list for combobox
List<string> companyList= new List<string>() { "", "Company1", "Company2" };
//Datsource list to combobox
cbCompanyName.DataSource = companyList;
//If form is set to import data and the billing address is not null
if (importAddress && StaticValues.billAddress != null)
{
//Fill all fields with data from Static Values class
cbCompanyName.Text = StaticValues.billAddress.CompanyName;
cbCountry.Text = StaticValues.billAddress.Country;
}
else
{
//Set country to US
cbCountry.SelectedIndex = 0;
}
however the line cbCompanyName.Text = StaticValues.billAddress.CompanyName; ran without writing any text to the combobox, until I set the selected index of the combobox to -1. What does setting the combobox selected index to -1 do that would change this as apposed to setting the selected index to 0?
Setting the SelectedIndex on a ComboBox to -1 deselects (SelectedItem is NULL). Setting to 0 selects the first item in Items
Combobox needs to know what is my value and display member,
giving the datasource is not enough for it.
I think you can use like this or
// comboBox.DisplayMember = "Text";
// comboBox.ValueMember = "Value";
int =0;
companyList.forEach(x=> comboBox.Items.Add(new { Text = x.toString(), Value =i++ }));
comboBox1.SelectedIndex = 0;
you can look this article
similar question and answers
I have a datagridview that contains list of subjects populated from Subject table from database.Columns include
Select(checkbox),
SubjectId,
SubjectName,
SubjectGroup.
Now I want if a user Selects on any of the desired rows, the corresponding SubjectId's should be added to a List. I have made and inserted into the desired table in the database.
The problem is that the new column of checkboxes I have added to this datagridview is not being detected.
My code is:
foreach (DataGridViewRow row in gvSubjectsOpted.Rows)
{
if (Convert.ToBoolean(gvSubjectsOpted.SelectedRows[0].Cells["SelectId"].Value=true))
{
olist.Add(gvSubjectsOpted.SelectedRows[0].Cells["SubjectId"].Value.ToString());
}
}
Late to the party. I had the same issue with trying to get the checkbox column by name, use the index instead. Here is a linq example assuming the checkbox is column 0 and the stored values for TrueValue and FalseVale are true and false respectively.
var checkedRows = from DataGridViewRow r in gvSubjectsOpted.Rows
where Convert.ToBoolean(r.Cells[0].Value) == true
select r;
foreach (var row in checkedRows)
{
olist.Add(row.Cells["SubjectId"].Value.ToString());
}
I realise this is an old post but I came across it and didn't think it was really answered in an efficient way so I thought I would add my method.
I have a similar block in my windows app. I read the values from the grid when the user clicks a button, and I want to know which rows they checked. As the checkboxes are in Cell 0 and the data I want is in Cell 1, I use the following code. Note the cast: it is important as it allows us the use the Where clause and therefore just a single line of code to get the collection of data. I could use the name of the cells instead of magic index numbers but then it would not fit your app so I put numbers instead (you should use names)
var checkedRows = dataGridView
.Rows
.Cast<DataGridViewRow>()
.Where(x => x.Cells[0].Value.ToString() == "1")
.Select(x => x.Cells[1]);
Note that this will give you an IEnumerable of type DataGridViewCell. If you want you can either add something like .Value.ToString() to the select or do this when you use your collection.
You question is similar to another SO question.
Check the answer of this Datagridview checkboxcolumn value and functionality.
Try this
foreach(GridViewRow r in gvSubjectsOpted.Rows)
{
GridViewCheckBoxColumn c = r.cells[0].Controls[0] as GridViewCheckBoxColumn;
if(c.Checked)
{
//Do something.
}
}
private void button1_Click(object sender, EventArgs e)
{
string subjId;
List<string> lines = new List<string>();
for (int i = 0; i < gvSubjectsList.Rows.Count; i++)
{
bool Ischecked =Convert.ToBoolean(gvSubjectsList.Rows[i].Cells["Select"].Value);
if (Ischecked == true)
{
subjId = gvSubjectsList.Rows[i].Cells["SubjectId"].Value.ToString();
lines.Add(subjId);
}
}
comboBox1.DataSource = lines;
}
//the most important thing is to set 'true' and 'false' values against newly added checkboxcolumn instead of '0' and '1'...that is,
CBColumn.FalseValue = "false";
CBColumn.TrueValue = "true";
I have a dropdown which I fill with data from a SQL server.
I fill the dropdown dynamically in the Page_Init() Event.
Depending on the Value, a ListItem is selected.
Now the problem is, that when I select another Item in the dropdown, that after the postback the selection is reset to the first item in the dropdownlist.
This here is a basic version of my code which does not work:
ArrayList AD_Group_Members = ActiveDirectory.GetMemberOfGroup("AD-Group");
ArrayList ListMachines = SQLQuery.Read("Database", "SELECT idVM, RandomString, Computername, Owner, FROM VM ORDER BY Computername");
for (int i = 0; i < ListMachines.Count; i++)
{
String RandomString = ((Hashtable)ListMachines[i])["RandomString"].ToString();
String Owner = ((Hashtable)ListMachines[i])["Owner"].ToString();
DropDownList DropDownList_Owner = new DropDownList();
DropDownList_Owner.ID = "DropDownList_Owner_" + RandomString;
DropDownList_Owner.Width = Unit.Percentage(95);
DropDownList_Owner.AutoPostBack = true;
DropDownList_Owner.EnableViewState = true;
DropDownList_Owner.SelectedIndexChanged += DropDownList_Owner_SelectedIndexChanged;
Div_Test.Controls.Add(DropDownList_Owner);
for (int y = 0; y < AD_Group_Members.Count; y++)
{
ListItem ListItem = new ListItem();
ListItem.Value = Owner;
ListItem.Text = ((Hashtable)AD_Group_Members[y])["GivenName"].ToString() + " " + ((Hashtable)AD_Group_Members[y])["Surname"].ToString();
if (((Hashtable)AD_Group_Members[y])["Username"].ToString().Equals(Owner))
{
ListItem.Selected = true;
}
DropDownList_Owner.Items.Add(ListItem);
}
}
Where is the issue in my code, that it doesn't work but the example.
Thank in Advance
You have to populate your dropdownlist under this condition on pageload.
Because on every post back your ddl is populated again and loses its selected index.
if (!IsPostBack)
{
//PopulateYourDDL here
}
You filled dropdown in Page_Init() which gets called in every postback and refill your dropdown and hence loses selectedindex.So you have to fill your dropdown inside !ispostback block
if (!IsPostBack)
{
//fill your dropdown here
}
I think the you should have unique values for the dropdown. Also as you have duplicate values in data value field the problem is occurring. It is looking for the first match and selecting it. You could try to fabricate the values which you could uniquely identify. Something like below:
COLUMN_NAME DATA_TYPE
a a_decimal
b b_decimal
c c_decimal
d d_int
e e_int
f f_varchar
g g_varchar
h h_varchar
i i_varchar
j j_varchar
Check out this Useful Source!!!
I hope it helps!!! Have a close look at those comments in the accepted answer section !!!
Also avoid using SelectedIndex_Changed() functions while dealing with Dynamically generated Web controls. Bind the DropdownList under Page_Init() or Page_PreInit(). If you want to perform some functions upon DropDownlist Selection Check out this! to determine the WebControl ID which is triggered and then perform an unique function in the Page_PreInit() or Page_Init().
I would like to know how can I get a column name from a gridview? by its number not by name.
like : Name|Age|Birthday: ( so name=0 , age=1 etc...)
thanks.
You can get it like this :
gv.HeaderRow.Cells[i].Text
Or like this :
gv.Rows[0].Cells[i].Text
Rows[0] should be your header row.
//// Header column names
int gridViewCellCount = yourGridView.Rows[0].Cells.Count;
// string array to hold grid view column names.
string[] columnNames = new string[gridViewCellCount];
for (int i = 0; i < gridViewCellCount; i++)
{
columnNames[i] = ((System.Web.UI.WebControls.DataControlFieldCell)(yourGridView.Rows[0].Cells[i])).ContainingField.HeaderText;
}
simply
GridView1.Rows[0].Cells[0].Text;
try this if you want to all the cells value from each of the rows
foreach (GridViewRow r in GridView1.Rows)
{
string s = r.Cells[0].Text;
string y = r.Cells[1].Text;
}
update:
try this
foreach (TableCell Tc in GridView1.HeaderRow.Cells)
{
//if you are not getting value than find childcontrol of TabelCell.
string sssb = Tc.Text;
foreach (Control ctl in Tc.Controls)
{
//Child controls
Label lb = ctl as Label;
string s = lb.Text;
}
}
Revisiting this old question.... it's possible to get the field names of the data bound to a GridView with this kind of code. This makes a dictionary of colnum and field name.
private static IDictionary<int, string> GetGridViewFieldNames(object grid)
{
var names = new Dictionary<int, string>();
var view = grid as GridView;
if (view != null) {
for (var i = 0; i < view.Columns.Count; i++) {
var field = view.Columns[i] as BoundField;
if (field != null) {
names.Add(i, field.DataField);
}
}
}
return names;
}
This is not the answer to the question. It is only the answer if you never change the header text in the gridview. The asker of the question wanted to get the database field name by index.
I've seen a number of "answers" which only provide the text in the selected row of a gridview, or the header text which both do not answer the question that was asked...
You may ask why? If you were going to do audits of updates in a system and wanted to compare old values and new values and only update if they change and want to indicate which field was updated how do you show the database table field name at the index of the loop.
For instance:
Protected Sub gv_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs)
Dim intValCount As Integer = Integer.Parse(e.NewValues.Count)
If intValCount > 0 Then
Dim i As Integer = 0
For i = 0 To intValCount - 1
If Not e.OldValues(i).Equals(e.NewValues(i)) Then
' values have changed, audit the change
Sys.Audits.General(intID, "the_database_table", <the table field by index(i)>, e.OldValues(i).ToString, e.NewValues(i).ToString)
End If
i += 1
Next
End If
End Sub
So the questions is how do you get the database table field name by index via code behind? I too have been searching for this and all the "answers" that I've seen are not the answers I think some of us are really looking for. All the mentioned methods I've seen here are not bullet proof references to a database tables field name.
Its easy: Here i read the gridview header text for each header cell and add them as new columns to a data table.
DataTable dt = new DataTable();
foreach(DataControlFieldHeaderCell column in yourGridview.HeaderRow.Cells)
{
dt.Columns.Add(column.Text.Trim().Replace(" ", ""));
}
//Make sure you do all this after yourGridview.DataBind();
//If you do not want to bind data first simply bind an empty list like so:
/* yourGridview.DataSource = new List<string>();
yourGridview.DataBind(); */
I want to set the selecteditem attribute for an ASP.Net dropdownlist control programmatically.
So I want to pass a value to the dropdownlist control to set the selected item where the item is equal to the passed value.
Assuming the list is already data bound you can simply set the SelectedValue property on your dropdown list.
list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";
list.DataBind();
list.SelectedValue = myValue.ToString();
The value of the myValue variable would need to exist in the property specified within the DataValueField in your controls databinding.
UPDATE:
If the value of myValue doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.
ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :
ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.
Here is the code I was looking for :
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));
Or
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));
Well if I understood correctly your question. The Solution for setting the value for a given dropdownlist will be:
dropdownlist1.Text="Your Value";
This will work only if the value is existing in the data-source of the dropdownlist.
If you need to select your list item based on an expression:
foreach (ListItem listItem in list.Items)
{
listItem.Selected = listItem.Value.Contains("some value");
}
Just Use this oneliner:
divisions.Items.FindByText("Some Text").Selected = true;
divisions.Items.FindByValue("some value").Selected = true;
where divisions is a dropdownlist control.
Hope it helps someone.
var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);
OR
foreach (var listItem in ctx.Items)
listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);
Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
On load of My Windows Form the comboBox will display the ClassName column of my DataTable as it's the DisplayMember also has its ValueMember (not visible to user) with it.
private void Form1_Load(object sender, EventArgs e)
{
this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
}
Safety check to only select if an item is matched.
//try to find item in list.
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;
ddlemployee.DataSource = ds.Tables[0];
ddlemployee.DataTextField = "Employee Name";
ddlemployee.DataValueField = "RecId";
ddlemployee.DataBind();
ddlemployee.Items.Insert(0, "All");