I'm trying get text of the selected drop down item
My drop down list is filled of db data
ad.Fill(dt);
drop1.DataSource = dt;
drop1.DataTextField = "zodys";
drop1.DataValueField = "zodys";
drop1.DataBind();
for example: word1, word2, word3, ...
All this is working fine, but when I try get text of the selected item I always get same text (text of the 1 item)
txtZip.Text = drop1.SelectedItem.Text;
I can almost guarantee your problem is that you're defining the above within Page_Load()? You need to only do this if you're not posting back, like so:
if(!IsPostBack)
{
ad.Fill(dt);
drop1.DataSource = dt;
drop1.DataTextField = "zodys";
drop1.DataValueField = "zodys";
drop1.DataBind();
}
This ensures that the value is not being reset each time prior to checking the SelectedItem.
I assume that you're databinding the dropdown also on postbacks in page_load. You should check for IsPostBack.
if(!IsPostBack)
{
ad.Fill(dt);
drop1.DataSource = dt;
drop1.DataTextField = "zodys";
drop1.DataValueField = "zodys";
drop1.DataBind();
}
Related
Edit: I am using window forms
So, I want to change a value of NumericUpDown if the selected value in combo box changes.
I placed a data table items with the columns ID, itemName, itemPrice and Stock and set the DisplayMember property to itemName.
I used this code:
cmb.DisplayMember = "itemName";
cmb.DataSource = items;
Then to get the whole row of the selected item I used
DataRow dataRow = ((DataRowView)cmbItems.SelectedItem).Row;
The problem is that in the UI, the combo box's selected item does not changes no matter what I do but the value of the selected item changes.
Like this.
I first thought that my unit is just lagging but its not. How do I fix this?
You can try this code to check if the combobox will get the selected item when you make your option.
dbConn.Open();// this allows you to edit the database
string sql = "Select * from database1";
SqlCommand dbComm = new SqlCommand(sql, dbConn);
SqlDataAdapter dbAdapter = new SqlDataAdapter(dbComm);
DataTable dt = new DataTable();
dbAdapter.Fill(dt);
cmbDescription.DataSource = dt;
cmbDescription.DisplayMember = "itemName";
cmbDescription.ValueMember = "Enter the column name here";
cmbDescription.Text = "";
cmbDescription.Items.Add(dt);
cdbConn.Close(); //close connection to save all your inputs,calculations to the database
I found out that my code is very confusing and the system seem to be having problems while executing, I've rewritten the whole code for this window form and it is working now.
I am having this problem with my datagridview where the first time it runs the delete button is on the last column, but everytime when i click on delete or adds, and call this printdataview() function.. the button is on the first column.
This function is called initially on Form1(), then calls everytime, I delete a record or add a record. I am using xml for storing data and add and remove records according, this printdataview() just simply refreshes the data on it.. and somehow it messes up, even the column length is messed the first time the datagridview was initialized and after.
Thanks Appreciate the feedback.
private void PrintDataView()
{
// clears the old data and repopulate it.
C_DB.DataSource = null;
XmlReader xmlFile;
xmlFile = XmlReader.Create(filename, new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0){
DataView dv = new DataView(ds.Tables[0]);
// first adds all rows after sorting today's list into datagridview
string Search = DateTime.Today.ToShortDateString();
dv.RowFilter = "DateTime LIKE '%" + Search + "%'";
dv.Sort = "DateTime ASC";
C_DB.DataSource = dv;
// then add the delete button if there is more than one row
if (dv.Count > 0 && C_DB.ColumnCount != 7 && C_DB.RowCount > 0)
{
// add button
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
C_DB.Columns.Add(btn);
btn.HeaderText = "Delete Row";
btn.Text = "Delete";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
}
// This scrolls to bottom
if (C_DB.RowCount > 10)
{
C_DB.FirstDisplayedScrollingRowIndex = C_DB.RowCount - 1;
}
}
else
{
C_ErrorMessage.Text = "No Data Found";
}
C_DB.Refresh();
xmlFile.Close();
}
Nvm, I found out what's wrong.
Instead of
// clears the old data and repopulate it.
C_DB.DataSource = null;
// I changed it to
C_DB.Columns.Clear();
Apparently nulling the datasource doesn't empty the structure from previously.
This also fixed my column widths.. which I set later
Thanks.
Note this is not a complete solution.
The problem you have that the Delete button appears at the end of the columns list the first time only and then changes position to first, is because when you added the button by executing the method PrintDataView(), you did not specify its position in the DataGridView. Use something like this:
//Your code
C_DB.Columns.Add(btn);
btn.HeaderText = "Delete Row";
btn.Text = "Delete";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
//Set the desired button position here
C_DB.Columns[btn.Name].DisplayIndex = 5; //Whatever value you want starting from zero
For more info. see: Full example on MS Site
Now, you can adjust each column width individually or set a property to max the width of all columns based on the contents as explained here:
DGV Column Size
I have a 3 Layer asp.net c# code. My BL:
public DataTable ddl()
{
base.Link();
string Query = "SELECT [nam], [idZone] FROM [zones] ORDER BY idZone";
DataTable Output_Q = base.SelectDataText(Query);
base.UnLink();
return Output_Q;
}
public void insert()
{
base.Link();
string Query = "INSERT INTO students (fnam, lnam, cod, idZone) VALUES ( '{0}', '{1}', '{2}', {3} )";
Query = string.Format(Query, fnam, lnam, cod, idZone);
base.commanddatatext(Query);
base.UnLink();
My Code:
page_load:
BL_students_new F = new BL_students_new();
DropDownList1.Items.Clear();
DropDownList1.DataSource = F.ddl();
DropDownList1.DataTextField = "nam";
DropDownList1.DataValueField = "idZone";
DropDownList1.DataBind();
btn_insert:
BL_students_new F = new BL_students_new();
F.fnam = TextBox1.Text.Trim();
F.lnam = TextBox2.Text.Trim();
F.cod = TextBox3.Text.Trim();
F.idZone = Convert.ToInt32(DropDownList1.SelectedItem.Value);
F.insert();
it saves every things but dropdownlist value. note that my ddl has text and int value and i need the value to be saved. but it fails. (My DA is OK too.)
From your comment above:
populating ddl is in page_load and inserting is in btn_insert
Page_Load happens before btn_Insert. This happens every time the page is requested, regardless of whether it's a "post back" or not. (After all, the page has to load into a usable state before it can even know the nature of the HTTP request.)
So what's happening is the following:
Bind the DropDownList options
Show the page to the user
User selects an option and submits
Re-bind the DropDownList options, losing whatever the user selected
Insert to database
A simple way to address this in WebForms is to wrap your DropDownList binding logic in a condition on IsPostBack. Something like this:
// in Page_Load:
if (!IsPostBack)
{
BL_students_new F = new BL_students_new();
DropDownList1.Items.Clear();
DropDownList1.DataSource = F.ddl();
DropDownList1.DataTextField = "nam";
DropDownList1.DataValueField = "idZone";
DropDownList1.DataBind();
}
That way you're only populating the DropDownList when the page is initially requested, not when the user is submitting the form.
I've 3 columns in DataGridView.
TextType
Combobox
TextType
I've bind Combobox of Datagridview like this:
BindingSource bindingSourceUnit = new BindingSource();
bindingSourceUnit.DataSource = datatableObject;
ColumnUnit.DataSource = bindingSourceUnit;
ColumnUnit.ValueMember = "id";
ColumnUnit.DisplayMember = "title";
This is showing all items in each row of the ComboBox second column.
Now I'm fetching data from a database and I want to display it in the DataGridView.
cmd = new OleDbCommand("SELECT * FROM Detail WHERE lr_id = #id", con);
cmd.Parameters.AddWithValue("#id", ID);
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DataGridViewRow row = (DataGridViewRow)dgItem.Rows[0].Clone();
row.Cells[dgItem.Columns["ColumnQty"].Index].Value = reader["qty"];
row.Cells[dgItem.Columns["ColumnUnit"].Index].Value = reader["unit"];
row.Cells[dgItem.Columns["ColumnDesc"].Index].Value = reader["detail"];
dgItem.Rows.Add(row);
}
}
In the while loop, "ColumnUnit" is my ComboboxType field. It's not allowing me to pre-select the value.
How can I set the value for this column?
Are you using the Ajax combo box control or the standard check box list control?
In any case you need to tell the control which combo value should be selected, so you will have to do a check to see what the value is coming back from your database call and then search for that in the combo box list of values and when you find the correct value set the "selected" property to true
Try
row.Cells[dgItem.Columns["ColumnUnit"].Index].Selected = row.Cells[dgItem.Columns["ColumnUnit"].Index].Value == reader["unit"] ? true : false;
Try casting the cell into a DataGridViewComboBoxCell and you should be able to change the value that way.
var tempCombo = (DataGridViewComboBoxCell)drNew.Cells[0].Value;
A solution (perhaps not the best one):
private void dataGridView1_DefaultValuesNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e)
{
e.Row.Cells["ColumnUnit"].Value = ... ; // set default value here
}
Using C#
Using SQL I populate a datatable with the results from a query.
then I created a datagrid that uses that datatable as its source.
The datagrid is already configured with a column of type DataGridViewComboBoxColumn.
The Combobox's datasource is another SQL loaded datatable that has two strings for each row. One string is the actual value I need, the second string is the user visible string.
The combobox is populated correctly with the information from the 2nd datatable and the values work as desired. When I save the data out of the datatable I'm getting the correct information for the combobox.
The problem comes into play when I try loading the saved SQL information back into that datagrid. The value doesn't seem to get bound to item the datatable.
Datagrid definition:
dgHeaders.DataSource = dtCSVHeaders;
dgHeaders.Columns["nIndex"].Visible = false;
if (!dgHeaders.Columns.Contains("colType"))
{
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "DB Field";
colType.DropDownWidth = 140;
colType.Width = 140;
colType.DataSource = dtFields;
colType.DataPropertyName = "szDBField";
colType.DisplayMember = "szVisualField";
colType.ValueMember = "szDBField";
colType.Name = "DB Field";
colType.DefaultCellStyle.NullValue = "--Select--";
dgHeaders.Columns.Add(colType);
}
First I tried to set the column name colType to the value I was populating in the dataRow but that didn't seem to work.
Since I couldn't figure out how to get the databinding to work, I decided I'd try to force the cell to the value I wanted so I tried this on the dataload.
... SQL load
foreach (DataRow drRow in dtLoad.Rows)
{
string szColumnName = drRow["szOrgColumnName"].ToString();
string szMatchName = drRow["szMatchColumn"].ToString();
DataRow drAdd = dtCSVHeaders.NewRow();
drAdd["nIndex"] = nLoop;
drAdd["szHeader"] = szColumnName;
dtCSVHeaders.Rows.Add(drAdd);
dgHeaders.Rows[nLoop].Cells[2].Value = szMatchName;
nLoop++;
}
But sadly that still doesn't set the value of the combobox.
I've got no errors or warnings on this code.
I'd prefer to let databinding take control and do its thing without me specifically setting the cell with the value. But if that's what I need to do then so be it...
Hmm, your code (as far as I seen) seem good.
I dont know what exactly is your "dtFields" object, but it should be dataTable.
I did a simple example of how it should be done.
Check it out:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add("column1", "Column name");
dataGridView1.Columns.Add(CreateComboBox());
//adding some rows:
dataGridView1.Rows.Add("a");
dataGridView1.Rows.Add("b");
}
private DataGridViewComboBoxColumn CreateComboBox()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
{
combo.Name = "comboColumn";
combo.HeaderText = "Selection";
combo.DataSource = GetDataForComboBox();
combo.DisplayMember = "Name";
combo.ValueMember = "Id";
}
return combo;
}
private DataTable GetDataForComboBox()
{
//this is your method to get the data from database
//in my exmaple I will simply add some example data:
DataTable table = new DataTable("ExampleData");
table.Columns.Add("Id", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(1, "Name 1");
table.Rows.Add(2, "Name 2");
table.Rows.Add(3, "Name 3");
return table;
}
}
This code works, and try to do the same, you only fill dataTable from dataBase. But if you want you can only try this exact code of mine, and you will see it work!
bye