Modifying a column in DGV to be a Combobox Bound to DataBase - c#

I created a view named "FamilyView" to join 2 tables(Families and SStatus) and replace an id in the first table(Families) by its name existing in the second table(SStatus) (the column is now called "Status")
This view is now displayed in a datagridview that the user can modify
Sda = new SqlDataAdapter("Select * from FamilyView",con);
Sda.Fill(ds);
dg.DataSource = ds.Tables[0];
dg.Refresh();
What i want is to transform the column cells "Status" to comboboxes containing all Names from SStatus
SqlDataAdapter sadapter = new SqlDataAdapter("Select * From SStatus", con);
DataSet ds1 = new DataSet();
sadapter.Fill(ds1);
i found this code:
DataGridViewComboBoxCell ComboColumn = (DataGridViewComboBoxCell)(dg.Rows[i].Cells[0]);
ComboColumn.DataSource = ds1.Tables[0];
ComboColumn.DisplayMember = "Name";
but i can't replace the cell
and this code but I'm not sure how to use it:
Adding bound combobox to datagridview
BindingSource StatusBD = new BindingSource();
StatusBD.DataSource = ds1;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Status";
colType.DropDownWidth = 90;
colType.Width = 90;
//colType.DataPropertyName = "Name";
colType.DataSource = ds;
colType.DisplayMember = "Name";
colType.ValueMember = "IdStatus";
dg.Columns.Insert(dg.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);

Your data source is empty: it should contain 2 tables: one with the SStatus and one with Families.
and then follow my as in your post:
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
BindingSource wizardBindingSource = new BindingSource();
wizardBindingSource.DataSource = dataSet;
wizardBindingSource.DataMember = "protocol"; // This is the table in the set
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = wizardBindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols"
Here idProtocol (which is referenced as protocol in the "pcap" table) is mapped to protocolName.

Related

C# Add Combobox and Checkbox for DataGridView Combined SQL Table

I have a table as following in SQL Database. Devicereg Table.
No | Parameter | DataTyp | Enable |
1 xxxx Int True
2 yyyy Int True
3 tttt String False
I want to show these data in DataGridView and its DataTyp column want to add Combobox with default value table cell value, Enable column want to add a checkbox with default value table cell value.
Combobox want to add the following list and the default value is one of following value.
Int
String
Floart
Following code, Combobox value adds all columns value in one combo box.
Code:
string connetionString = null;
SqlConnection connection;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
bool st = false;
DataSet ds = new DataSet();
connection = new SqlConnection(connetionString);
sql = "select * from Devicereg";
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand(sql, connection);
adapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = null;
dataGridView1.ColumnCount = 0;
dataGridView1.DataSource = ds.Tables[0];
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = ds.Tables[0];
dc.ValueMember = "Datatyp";
dataGridView1.Columns.Add(dc);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Example Photo:
Edit 1:
I have done it but how to display only defined items in the dropdown.
Code:
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = ds.Tables[0];
dc.DataPropertyName = "Datatyp";
dc.ValueMember = "Datatyp";
dc.DisplayMember = "Datatyp";
I have 36 rows and all rows Datatyp values shows. I want specific items to select like Int, Flort, Strings only.
Output:
Edit 2:
If I set like the following code, I got error message.
DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
dc.DataSource = new List<string> { "Int", "String", "Flort" };
dc.DataPropertyName = "Datatyp";
dc.ValueMember = "Datatyp";
dc.DisplayMember = "Datatyp";
Error:
To import the DataTyp from database to DataGridViewComboBoxColumn, please refer to the following steps.
First, add the columns to datagridview.
Set the DataTyp's columntype to DataGridViewComboBoxColumn, and set its DataSource like:
Next, set Enable columntype to DataGridViewCheckBoxColumn.
Or via code:
var colNo = new DataGridViewTextBoxColumn
{
HeaderText = "No",
Name = "No"
};
var colParameter = new DataGridViewTextBoxColumn
{
HeaderText = "Parameter",
Name = "Parameter"
};
var colDataTyp = new DataGridViewComboBoxColumn
{
HeaderText = "DataTyp",
Name = "DataTyp",
DataSource = new List<string> { "Int", "String", "Float" }
};
var colEnable = new DataGridViewCheckBoxColumn
{
HeaderText = "Enable",
Name = "Enable"
};
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { colNo, colParameter, colDataTyp, colEnable });
Then fill the datagridview via the code below.
DataSet ds;
string connetionString = #"Connection String";
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From Devicereg", conn);
ds = new DataSet();
sda.Fill(ds, "T1");
}
DataGridViewComboBoxCell typeCell;
foreach (DataRow row in ds.Tables[0].Rows)
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells["No"].Value = row[0];
dataGridView1.Rows[index].Cells["Parameter"].Value = row[1];
typeCell = (DataGridViewComboBoxCell)(dataGridView1.Rows[index].Cells["DataTyp"]);
typeCell.Value = row[2].ToString().Trim();
dataGridView1.Rows[index].Cells["Enable"].Value = row[3];
}
The result,

Columns are said to be null while they really aren't C# WinForms

I have created a datagridview with a nested relation that lists an incident and its activities per row. This by using DevExpress:
My problem is, is that I do not have access right to the columns at all.
This means that I can't set the hidden columns, column widths and so an all by a NullReferenceException.
This is my code that I use:
private void DisplayData()
{
conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=Ticketing;Integrated Security=true");
daIncidents = new SqlDataAdapter("Select * from incidents", conn);
daActivities = new SqlDataAdapter("Select * from Activity", conn);
ds = new DataSet();
daIncidents.Fill(ds, "Incidents");
daActivities.Fill(ds, "Activities");
DataColumn keyColumn = ds.Tables["Incidents"].Columns["IncidentID"];
DataColumn foreignKeyColumn = ds.Tables["Activities"].Columns["IncidentID"];
ds.Relations.Add("IncidentsActivities", keyColumn, foreignKeyColumn);
gridControl.DataSource = ds.Tables["Incidents"];
gridControl.ForceInitialize();
GridView gridView = new GridView(gridControl);
gridControl.LevelTree.Nodes.Add("IncidentsActivities", gridView);
gridView.ViewCaption = "Activities";
//gridView.Columns["ActivityID"].ReadOnly = true;
//gridView.Columns["Description"].Width = 40;
}
Why does it say that the columns are null if they really aren't? I have tried using intas index but same problem.
Change:
gridView.ViewCaption = "Activities";
to:
gridView.ViewCaption = "Activities";
gridView.PopulateColumns();

Adding a combo Box to a Data grid View

I'm trying to add a combo Box to the datagrid View. This is the code for the datagrid view
SqlDataAdapter da = new SqlDataAdapter("SELECT pid, pdtName, amount, Qty,day, cat from purchase where year=#year and month=#month", ConnectionInfo.con);
da.SelectCommand.Parameters.AddWithValue("#year", comboBox3.Text);
da.SelectCommand.Parameters.AddWithValue("#month", comboBox2.Text);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
this.dataGridView1.Columns[0].HeaderText = "number";
this.dataGridView1.Columns[0].ReadOnly = true;
this.dataGridView1.Columns[0].Visible = false;
this.dataGridView1.Columns[1].HeaderText = "name";
this.dataGridView1.Columns[2].HeaderText = "amount";
this.dataGridView1.Columns[3].HeaderText = "number";
this.dataGridView1.Columns[4].HeaderText = "day";
this.dataGridView1.Columns[5].HeaderText = "category";
for column 5 in the datagrid view I'm trying to set it as a combo box and read the category names from the category table in my database.
I'm starting with this code but I don't know how to complete it
string query = "select distinct cat from purchase ";
SqlDataAdapter da2 = new SqlDataAdapter(query, ConnectionInfo.con);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "purchase");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "cat";
cmb.Name = "cmb";
cmb.DataSource=ds2
Can you point out whats wrong in my code, or help me in another way to solve my problem
You need to format each column using a DataGridViewTextBoxColumn or DataGridViewComboBoxColumn and add it to the DataGridView. Be sure to set AutoGenerateColumns to false. Something like:
dataGridView1.Columns.Clear();
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Description";
column.Name = "Description";
column.HeaderText = "Description";
column.Width = 150;
//column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns.Add(column)
DataGridViewComboBoxColumn ccolumn = new DataGridViewComboBoxColumn();
ccolumn.DataPropertyName = "cmb";
ccolumn.Name = "cmb";
ccolumn.HeaderText = "Cat";
ccolumn.Width = 65;
ccolumn.DataSource = ds2;
ccolumn.DisplayMember = "cat";
ccolumn.ValueMember = "cat";
dataGridView1.Columns.Add(ccolumn);
Do all the columns like this before you assign the DataSource to the DataGridView.

Dataview doesn't get datagridview column header properly

Though I set a new column header in datatable before assigning it to datagridview, when I call this datagridview from dataview I get old column headers. Here is a part of my code:
DataSet ds = new DataSet();
grid.DataSource = null;
ds.ReadXml(path);
var dt = ds.Tables[0];
dt.Columns["Name"].Caption = "Descr";
dt.Columns["Account"].Caption = "ACNT"; // I tried both .Caption and .Columname
grid.DataSource = ds.Tables[0];
I also tried changing column header after implementation of datagridview, but still without any result:
grid.Columns[0].HeaderText = "Descr";
How can I set a column header that later dataview can read it properly?
you need to set the DataPropertyName, in your case:
dt.Columns["Name"].DataPropertyName = "Name";
dt.Columns["Name"].HeaderText = "Descr";
dt.Columns["Account"].DataPropertyName = "Account";
dt.Columns["Account"].HeaderText = "ACNT";
You could try the following below:
grid.DataSource = null;
using (DataSet ds = new DataSet())
{
ds.ReadXml(path);
var dt = ds.Tables[0];
sda.Fill(dt);
//Set AutoGenerateColumns False
dataGridView1.AutoGenerateColumns = false;
//Set Columns Count
dataGridView1.ColumnCount = 3;
//Add Columns
dataGridView1.Columns[0].Name = "CustomerId";
dataGridView1.Columns[0].HeaderText = "Customer Id";
dataGridView1.Columns[0].DataPropertyName = "CustomerID";
dataGridView1.Columns[1].HeaderText = "Contact Name";
dataGridView1.Columns[1].Name = "Name";
dataGridView1.Columns[1].DataPropertyName = "ContactName";
dataGridView1.Columns[2].Name = "Country";
dataGridView1.Columns[2].HeaderText = "Country";
dataGridView1.Columns[2].DataPropertyName = "Country";
dataGridView1.DataSource = dt;
}
}
Another way,you could try with less lines of code. Use the Design view yourGrid->smart tag -> edited the column ->Data->DataProperty ->(Add your db column Name).
Once that is Done you can just call your grid.
private void PopulateGrid()
{
grid.AutoGenerateColumns = false;
List<Your table> yourTable_List = GetMethodOfTheData();
var source = new BindingSource(yourTable_List , null);
grid.DataSource = source;
}

How to show dataset changes in datagridview?

I have a code like below.
I a dataset and two tables in it. And there is a relation between those tables.
DataSet ds = new DataSet();
DataTable dtPerson = new DataTable("Persons");
DataTable dtBooks = new DataTable("Books");
ds.Tables.Add(dtPerson);
ds.Tables.Add(dtBooks);
dtPersons = LoadPersons();
dtBooks = LoadBooks();
ds.Relations.Add(new DataRelation("PersonBookRel",dtPersons.Columns["P_ID"],dtBooks.Columns["P_ID"]));
gridPersons.DataSource = ds;
gridPersons.DataMember = "Persons";
gridBooks.DataSource = ds;
gridBooks.DataMember = "Books";
The problem is that, when i add new row to dtPerson, gridPerson does not show new records.
Code is below.
DataRow row = dtPerson.NewRow();
row[0] = "Joe";
row[1] = "Black"
row[2] = 18;
...
dtPerson.Rows.Add(row);
ds.AcceptChanges();
So what is the problem? How to solve it?

Categories