I have a GridView named gridview1 and I am assigning it the data through a datatable as below.
SqlConnection con = new SqlConnection(cls_Connection.connection);
con.Open();
SqlDataAdapter sd = new SqlDataAdapter();
sd.SelectCommand = new SqlCommand("select d.id,e.Name,d.type from Employee_Details e join designation d on e.id=d.id and d.type='"+atten_cmb_type.Text+"'",con);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
The gridview contains the data and only shows it in the column when the column is clicked and hides it again. Note:I am doing all this in the ComboBox SelectedIndexChanged event.
And I had a ListView before which I deleted and used a GridView instead. All other gridviews in my application work fine.
this is my designer code
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(456, 111);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.Size = new System.Drawing.Size(768, 315);
this.dataGridView1.TabIndex = 20;
Related
How to get the selected index or selected value of a combobox that was created by a function? I created a form and added comboboxes and textboxes. The value of a combobox affects the value of the next one and so on:
Form Edit = new Form();
ComboBox contract = new ComboBox();
ComboBox finyear = new ComboBox();
Button Update = new Button();
Button Cancel = new Button();
Label fyLbl = new Label();
Label ContractLbl = new Label();
SQLiteConnection _connection = new SQLiteConnection();
_connection = new SQLiteConnection("Data Source=mydb.db;Version=3");
_connection.Open();
string qr = "SELECT ContractId,Name FROM Contract";
using (SQLiteDataAdapter sda = new SQLiteDataAdapter(qr, _connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DataRow dataRow = dt.NewRow();
dataRow[0] = 0;
dataRow[1] = "Select...";
dt.Rows.InsertAt(dataRow, 0);
contract.DataSource = dt;
contract.DisplayMember = "Name";
contract.ValueMember = "ContractId";
}
int contractId = contract.SelectedIndex;
The last line is always null. Comboboxes created with the Designer can work with SelectedIndexChanged but since my controls are not accessible outside this function, what can I do?
I have the following code to populate 3 comboboxes:
private void PopulateDDLs()
{
SqlConnection connection;
SqlCommand command;
SqlDataReader reader;
DataTable dt;
using (connection = new SqlConnection("connection string here"))
{
using (command = new SqlCommand("sql query here", connection))
{
connection.Open();
using (reader = command.ExecuteReader())
{
dt = new DataTable();
dt.Load(reader);
ddl1.ValueMember = "col1";
ddl1.DisplayMember = "col2";
ddl1.DataSource = dt;
ddl2.ValueMember = "col1";
ddl2.DisplayMember = "col2";
ddl2.DataSource = dt;
ddl3.ValueMember = "col1";
ddl3.DisplayMember = "col2";
ddl3.DataSource = dt;
}
connection.Close();
}
}
}
However, when I execute this program, and make a selection from one of the comboboxes, the same value automatically gets selected from the other comboboxes. Any idea why this is happening and how to stop it from happening more importantly?
If I create 3 functions, 1 for each combobox, then everything works fine.
This project is a Word Document level project for Word 2010 created using .NET-4.0 using VS2013.
New much improved solution:
A DataSource is more than just the data.
There is hidden default BindingSource that makes the ComboBoxes follow.
To avoid this coupling and also the data replication in the first version of this answer, all you need to do is create a separate BindingSource for each ComboBox. These share the DataTable but have each its own rowPointer:
BindingSource bS1, bS2, bS3;
..
..
..
..
dt = new DataTable();
dt.Load(reader);
bS1 = new BindingSource();
bS1.DataSource = dt;
bS2 = new BindingSource();
bS2.DataSource = dt;
bS3 = new BindingSource();
bS3.DataSource = dt;
..
ddl1.DataSource = bS1 ;
ddl2.DataSource = bS2 ;
ddl3.DataSource = bS3 ;
..
..
Now the ComboBoxes can be changed independently.
Note: My first version worked but was the wrong way do it. Sorry..!
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";
I'm working with GridView I need to add button to an existing column (turn an existing column to buttoncolumn) not add new column with buttons. my column called Volunteers.
see the code below:
public void showCourse()
{
SqlCommand com = new SqlCommand("SELECT [Course_ID],[Course_Name],[Course_Type],[Course_Hours],[Course_Duration],[Course_Place],[Trainer_ID],[Volunteers] FROM [VolunteersAffairs].[dbo].[Course_Info]", con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet dats = new DataSet();
da.SelectCommand = com;
da.Fill(dats, "Course_Info");
dataGridViewShowCourse.DataSource = dats.Tables["Course_Info"];
DataGridViewButtonXColumn bcx =
dataGridViewShowCourse.Columns["Volunteers"] as DataGridViewButtonColumn;// Like I did nothing
bcx.UseColumnTextForButtonValue = true;
bcx.Text = "ADD";
bcx.Name = "MyButton";
}
the error show: Object reference not set to an instance of an object.
I know add new column with button but I dont want do that, I need to add button to an existing column. The code for add new column with button like below
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = true;
col.Text = "ADD";
col.Name = "MyButton";
dataGridViewShowCourse.Columns.Add(col);
Thanks
You can add new button column before setting your DataSource with correct settings like this:
public void showCourse()
{
SqlCommand com = new SqlCommand("SELECT [Course_ID],[Course_Name],[Course_Type],[Course_Hours],[Course_Duration],[Course_Place],[Trainer_ID],[Volunteers] FROM [VolunteersAffairs].[dbo].[Course_Info]", con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet dats = new DataSet();
da.SelectCommand = com;
da.Fill(dats, "Course_Info");
if(dataGridViewShowCourse.Columns["MyButton"] == null){
var col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = true;
col.Text = "ADD";
col.Name = "MyButton";
col.DataPropertyName = "Volunteers"; //<-- this is very important
dataGridViewShowCourse.Columns.Add(col);
}
dataGridViewShowCourse.DataSource = dats.Tables["Course_Info"];
}
However I suggest you should remove the Volunteers from the SELECT and add the new button column yourself.
Set the column to the last:
col.DisplayIndex = dataGridViewShowCourse.Columns.Cast<DataGridViewColumn>()
.Count(col=>col.Visible) - 1;
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.