How to get Datasource() for Dropdownbox C# ASP.NET - c#

I have table tblDepartments with columns DeptID, Department, Description. I also have dropdownbox drpDepartments. I want to display the contents of column Department on the dropdownbox. I tried using this C# code for winforms but it didn't work:
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DisplayMember = "Department";
drpDepartments.ValueMember = "DeptID";
drpDepartments.Text = "Choose Department";
How do I do it using ASP.NET C#? Thanks.
New code (still not working)
sConn = new SqlConnection(sStr);
daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
dsEmp = new DataSet();
dsDep = new DataSet();
daEmp.Fill(dsEmp, "tblEmployee");
daDep.Fill(dsDep, "tblDepartment");
dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };
DataTable dt=new DataTable();
daDep.Fill(dt);
drpDepartments.DataTextField = "Department";
drpDepartments.DataValueField = "DeptID";
drpDepartments.DataSource = dt;
drpDepartments.DataBind();

You have to call it like this in asp.net webForms
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];// Set DataSource Table First
drpDepartments.DataTextField = "Department";// Set Column Name of DataTable to set as Text Field
drpDepartments.DataValueField = "DepartmentID";// Set Column Name of DataTable to set as Value Field
drpDepartments.DataBind();
You must be using it from using System.Web.UI.WebControls; namespace. It seems like you were using winforms namespaces.
DataTextField is equivalent to DisplayMember and ValueMember is equivalent to DataValueField.

Did you call DataBind()?
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DisplayMember = "Department";
drpDepartments.ValueMember = "DepartmentID";
drpDepartments.Text = "Choose Department";
drpDepartments.DataBind();

drpDepartments.DataSource = ds1;
drpDepartments.DataTextField = "textcol";
drpDepartments.DataValueField = "valuecol";
drpDepartments.DataBind();
after doing this in btn_save method
add this..
cmd.Parameters.AddWithValue("#a", drpDepartments.SelectedValue);
hope it helps.

Related

Data grid view not showing data from mysql table

Im trying to get data in data grid view . this code works fine if i use this query :- "Select * from employee.transaction"
But when im trying to put the conditions it does not give any output (just shows a blank table)
My table has month,year column of type Int.Im using mysql server 5.6.25
I cant find the problem with my code.Please help.Thx in advance.
private void load_data_Click(object sender, EventArgs e)
{
string constring = "datasource = localhost;port = 3306;username = ****;password = ****";
MySqlConnection conDataBase = new MySqlConnection(constring);
var cmdDataBase = conDataBase.CreateCommand();
cmdDataBase.CommandText = #"select * from employee.transaction where department = #department AND month = #month AND year = #year";
cmdDataBase.Parameters.AddWithValue("#department", this.department.Text);
cmdDataBase.Parameters.AddWithValue("#month", this.dateTimePicker1.Value.Month);
cmdDataBase.Parameters.AddWithValue("#year", this.dateTimePicker1.Value.Year);
try
{
// here im trying to show table in datagrid view
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
//here im trying to make a excel file which would contain what is currently being displayed in the datagrid view
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
ds.Tables.Add(dbdataset);
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The problem could be, as mentioned by #Bjorn-Roger in the comments, that both 'month' and 'year' are keywords in SQL.
I would suggest you try :
select * from employee.transaction where department = #department AND [month] = #month AND [year] = #year
P.S: Notice the use of [] with the fields 'month' and 'year'.
Edit 1
Also, you might want to check if the date format of the input fields 'month' and 'year' is same as that of database table fields.

Create and Bind DataGridViewColumn with query results. Add it to DataGridView

I am desperately trying to add a DataGridViewComboBoxColumn to my DataGridView programatically. Here is the Code I've got so far.
DataTable dt = new DataTable();
dt = _userBL.getUsersTable().DefaultView.ToTable(false, "Person_ID", "FirstName", "LastName", "Title", "Username");
dataGridView1.DataSource = dt;
DataGridViewComboBoxColumn ComboBoxCell = new DataGridViewComboBoxColumn();
ComboBoxCell.Name = "State";
ComboBoxCell.ValueMember = "State";//ComboBoxCell.DisplayMember = "State";
ComboBoxCell.DisplayMember = "State";
ComboBoxCell.DataSource = _userBL.getUsersTable().DefaultView.ToTable(false, "State");
this.dataGridView1.Columns.Add(ComboBoxCell);
But i get no data in the comboboxcolumn, and since I added DataSource, I cannot add items (Active,Inactive) in it. Also, when I click it a small dropdown should appear, even for empty comboboxes, but it does not.
Thanks in advance!
Try this one..
DataGridViewComboBoxColumn combo = (DataGridViewComboBoxColumn)dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].OwningColumn;
dt.Clear();
da = new SqlDataAdapter("select name from tblData", con);
da.Fill(dt);
combo.DataSource = dt;
combo.DisplayMember = "name";

How to fill DataGridViewComboBoxColumn from a database table column without using datareader

Here is my code:
SqlDataAdapter GridDataAdapter = new SqlDataAdapter(query, con);
DataSet GridDataSet = new DataSet();
GridDataAdapter.Fill(GridDataSet, tbln);
dataGridView1.DataSource = GridDataSet;
DataGridViewComboBoxColumn dgvCB = new DataGridViewComboBoxColumn();
dataGridView1.DataMember = tbln;
Here, I want to fetch data for DataGridViewComboBox from a database table column.
How can I fill the DataGridViewComboBoxColumn without using a DataReader?
You already have the dataset filled, you could just iterate over the row collection if it contains the values that you want the DGVCombo to contain. So, the most straightforward way would be something along the lines of:
foreach(DataRow r in GridDataSet.Tables[0].Rows)
{
dgvCB.Items.Add(r["MyColumn"]);
}
Where .Tables[0] has the column("MyColumn") that you are looking for...
This should be what you need...
DataGridViewComboBoxColumn dgvCB = new DataGridViewComboBoxColumn();
dgvCB.Name = "lastname";
dgvCB.DataSource = tbln;
dgvCB.HeaderText = "Last";
//uncomment this to actually select the value in the combo box
//dgvCB.DataPropertyName = "lastname";
dgvCB.ValueMember = "lastname";
dataGridView1.Columns.Add(dgvCB);

Can't get value from dropdownbox to database

I have a webform wherein the admin will add new records to database. The form has 1 dropdownbox drpDepartments and a few textboxes EmployeeID, Fname, Lname, etc. I can add a new record but the option chosen from the dropdownbox isn't changing. It's always the first value. Here are tables tblEmployee and tblDepartment.
Here's my Page_Load() code:
sConn = new SqlConnection(sStr);
daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
dsEmp = new DataSet();
dsDep = new DataSet();
daEmp.Fill(dsEmp, "tblEmployee");
daDep.Fill(dsDep, "tblDepartment");
dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DataTextField = "Description";
drpDepartments.DataValueField = "DeptID";
drpDepartments.DataBind();
And the btnAdd_Click() code:
cb = new SqlCommandBuilder(daEmp);
DataRow dRow = dsEmp.Tables["tblEmployee"].NewRow();
dRow["EmployeeID"] = txtID.Text;
dRow["Lname"] = txtLname.Text;
dRow["Fname"] = txtFname.Text;
dRow["Mname"] = txtMname.Text;
dRow["Address"] = txtAddress.Text;
dRow["Email"] = txtEmail.Text;
dRow["Phone"] = Convert.ToInt64(txtPhone.Text);
dRow["Jobtitle"] = txtJobtitle.Text;
dRow["Salary"] = txtSalary.Text;
dRow["DeptID"] = drpDepartments.SelectedValue;
dsEmp.Tables["tblEmployee"].Rows.Add(dRow);
daEmp.Update(dsEmp, "tblEmployee");
dsEmp.Tables["tblEmployee"].AcceptChanges();
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "test", "<script>alert('New record added!');</script>");
Refresh();
The binding of dropdown must be only in !IsPostBack
if(!IsPostBack)
{
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];// Set DataSource Table First
drpDepartments.DataTextField = "Department";// Set Column Name of DataTable to set as Text Field
drpDepartments.DataValueField = "DepartmentID";// Set Column Name of DataTable to set as Value Field
drpDepartments.DataBind();
}
If you bind the DropDownList in postback event, the dropdown will be re-binded in the the button_click (in the page_load) event and the value set by the user will be lost.

Adding bound combobox to datagridview

The scenario is almost the same as http://arsalantamiz.blogspot.com/2008/09/binding-datagridview-combobox-column.html. but I can't get it working on c#...
I have mySql db with two tables:
1. protocols
2. pcapdata
In protocols tables I have a two fields: idprotocols and protocolName
Int the pcaps table I have wizardProtocol (which is "linked" to the idprotocols field)
What I'm trying to get is to have a combobox containing names which will replace the wizardprotocol field. Next, If the user updates the "names" combobox the wizardProtocol will be changed accordingly (so I will be able to update the changes in the database accordingly).
Now, after reading some information on the net: I've written the following code:
public void Bind(ref DataGridView dataGridView)
{
try
{
mySqlDataAdapter = new MySqlDataAdapter(SELECT_ALL_PCAP, _con);
mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();
dataSet = new DataSet();
mySqlDataAdapter.Fill(dataSet, "pcap");
MySqlDataAdapter adp2 = new MySqlDataAdapter(SELECT_ALL_PROTOCOL, _con);
MySqlCommandBuilder builder = new MySqlCommandBuilder(adp2);
adp2.UpdateCommand = builder.GetUpdateCommand();
adp2.DeleteCommand = builder.GetDeleteCommand();
adp2.InsertCommand = builder.GetInsertCommand();
adp2.Fill(dataSet, "protocol");
bindingSource = new BindingSource();
bindingSource.DataSource = dataSet;
bindingSource.DataMember = "pcap";
dataGridView.DataSource = bindingSource;
dataGridView.Columns["length"].ReadOnly = true;
dataGridView.Columns["length"].DefaultCellStyle.ForeColor = System.Drawing.Color.SandyBrown;
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = bindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols";
dataGridView.Columns.Insert(dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);
}
catch (System.Exception e)
{
MessageBox.Show(e.ToString());
}
}
I'm trying to manipulable the DisplayMember property, but I fail (I know that the problem is with probably with my data-binding, but I can't figure it out...)
UPDATE: Thanks to the answer, I'm re-attaching the fixed code
mySqlDataAdapter = new MySqlDataAdapter(SELECT_ALL_PCAP, _con);
mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();
dataSet = new DataSet();
mySqlDataAdapter.Fill(dataSet, "pcap");
MySqlDataAdapter adp2 = new MySqlDataAdapter(SELECT_ALL_PROTOCOL, _con);
MySqlCommandBuilder builder = new MySqlCommandBuilder(adp2);
adp2.UpdateCommand = builder.GetUpdateCommand();
adp2.DeleteCommand = builder.GetDeleteCommand();
adp2.InsertCommand = builder.GetInsertCommand();
adp2.Fill(dataSet, "protocol");
bindingSource = new BindingSource();
bindingSource.DataSource = dataSet;
bindingSource.DataMember = "pcap";
dataGridView.DataSource = bindingSource;
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
BindingSource wizardBindingSource = new BindingSource();
wizardBindingSource.DataSource = dataSet;
wizardBindingSource.DataMember = "protocol";
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = wizardBindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols";
dataGridView.Columns.Insert(dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);
The most obvious thing that you are doing wrong is that you use the same binding source for both your datagridview and for your comboboxcolumn. If you look at the example you provided you'll notice that they create a second bindingsource productBindingSource.
So what you need to do is create a bindingsource (let's call it wizardProtocolBindingSource) which you then fill with the data from your protocols table. This becomes the datasource for your combobox column.
The key code looks something like this:
// You bind the datagridview just as before
// this dataset should have the idprotocols field which is your foreign key
// to the protocols table - you will probably want this to be hidden.
bindingSource = new BindingSource();
bindingSource.DataSource = dataSet;
bindingSource.DataMember = "pcap";
dataGridView.DataSource = bindingSource;
// hide the foreign key column
dataGridView.Columns["idProtocols"].Visible = false;
// here we populate your comboboxcolumn binding source
wizardProtocolBindingSource= new BindingSource();
// this dataset is from the protocols table
wizardProtocolBindingSource.DataSource = dataSet;
// Add the combobox column
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataSource = wizardProtocolBindingSource;
// The DataPropertyName refers to the foreign key column on the datagridview datasource
colType.DataPropertyName = "wizardProtocol";
// The display member is the name column in the column datasource
colType.DisplayMember = "protocolName";
// The value member is the primary key of the protols table
colType.ValueMember = "idprotocols";
// I usually just add the column but you can insert if you need a particular position
dataGridView.Columns.Add(colType);
The above should work for you, though not knowing the names of your dataset columns I had to guess a little.

Categories

Resources