Implement value from datatable into datagridview - c#

I'm trying to change the color of 3 cells based on the corresponding database value attached to the physician initials. In other words, the physician has a specific color for the cell background when they view their patients. The database "physicians" has three columns (Physician Name, Initials, Color). Below is some of the code.
void PhysicianColorTreatPrep()
{
string ColorQuery = "SELECT * FROM physicians";
SqlConnection connectionstring = new SqlConnection(constring);
connectionstring.Open();
DataTable dsDocColor = new DataTable();
SqlDataAdapter adapterDocColor = new SqlDataAdapter(ColorQuery, constring);
adapterDocColor.Fill(dsDocColor);
foreach (DataGridViewRow row in datagridviewTreatmentPrep.Rows)
{
DataRow[] result = dsDocColor.Select("Color WHERE Initials = "+row.Cells["Primary_Onc"].Value.ToString()+"");
row.Cells["Last_Name"].Style.BackColor = //Color retrieved from datatable based on datagridview value
row.Cells["First_Name"].Style.BackColor = //Color retrieved from datatable based on datagridview value
row.Cells["Primary_Onc"].Style.BackColor = //Color retrieved from datatable based on datagridview value
}
}

#ChetanRanpariya Thanks for asking the right questions. I managed to solve it. Below is the code.
DataRow[] result = dsDocColor.Select("Initials = '"+row.Cells["Primary_Onc"].Value.ToString()+"'");
string DocColor = result[0][2].ToString();
row.Cells["Last_Name"].Style.BackColor = System.Drawing.Color.FromName(DocColor);
row.Cells["First_Name"].Style.BackColor = System.Drawing.Color.FromName(DocColor);
row.Cells["Primary_Onc"].Style.BackColor = System.Drawing.Color.FromName(DocColor);

Related

Set datagridview checkbox value while data from database in C# Windowsform

I have a datagridview in windows control form where I insert a checkbox column beside a data table queried from MYSQL database
private void ControlForm_Load(object sender, EventArgs e)
{
DataGridViewCheckBoxColumn ChkboxCol = new DataGridViewCheckBoxColumn();
ChkboxCol.HeaderText = "Checkbox";
ChkboxCol.Width = 50;
ChkboxCol.Name = "Checkbox";
ChkboxCol.TrueValue = true;
ChkboxCol.FalseValue = false;
dataGridView1.Columns.Insert(0, ChkboxCol);
int ColCount = dataGridView1.ColumnCount;
dataGridView1.DataSource = tablequery();
}
public DataTable tablequery()
{
MY_DB DB = new MY_DB();
string query = "SELECT * FROM sometable";
MySqlCommand cmd = new MySqlCommand(query, DB.GetConnection);
MySqlDataAdapter adapter = new MySqlDataAdapter();
DataTable table = new DataTable();
adapter.SelectCommand = cmd;
adapter.Fill(table);
return table;
}
In the "sometable" table in MySQL, I have set the data type to be TINYINT (which arise after I select Boolean) in the "Checkbox_Value" column and I have set the number to be 0 or 1. I would want my results on the checkbox column of my datagrid to reflect as checked if the "Check_Value" of a particular entry to be 1 or unchecked if the "Check_value" of another particular entry is 0. The number of entries in the "sometable" and the value of the "Check_Value" would change and I wish this checkbox could reflect the checked status dynamically.
Thank you very much for any suggestion or advice.
I have included the table of my DB
enter image description here
where the column "XXXX" is the set_active column

populate DataGridView from database and TextBox

Basically I want to add another column from a TextBox along with values I have queried from the database. I want my datagridview to show something like
|itemcode|Category|itemDescription|unitcost|quantity|
where itemcode, Category, itemDescription, unitcost is from database and quantity is from a text box input.
private void btnAddToCart_Click(object sender, EventArgs e)
{
con.OpenConnection();
MySqlCommand cmd = con.connection.CreateCommand();
string search = txtSearchProduct.Text;
string quantity = txtQuantity.Text;
string query = "SELECT itemcode, Category, itemDescription, unitcost FROM tblprowareproducts WHERE itemDescription LIKE ?search";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("?search", "%" + search + "%");
using (MySqlDataAdapter mda = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
mda.Fill(dt);
dgvCart.DataSource = dt;
}
}
Is there a way to add another column after unitcost named quantity and the value of it comes from a TextBox?
There are different solutions for the problem, for example you can add the column to DataTable this way:
DataTable dt = new DataTable();
mda.Fill(dt);
var quantity = dt.Columns.Add("quantity", typeof(int));
quantity.DefaultValue = int.Parse(txtQuantity.Text);
dt.AsEnumerable().ToList().ForEach(r =>
{
r[quantity] = quantity.DefaultValue;
});
dgvCart.DataSource = dt;
Note 1: You may want to use TryParse to get the integer value from text.
Note 2: Default value of column applies to the column when adding the row. So to apply it to existing rows, you need to use a loop like what I did. For new rows that you add after that, it will be applied automatically.

How can you add combobox to datagridview from datatable?

Here is a code where I add value to datagridview from datatable. The "First" and "Third" column of the datagridview have been filled with data from the datatable. The problem is for the "Second" and the "Forth" column, as I have to make it a combobox for the user to choose. Each combobox has default value which is "columnDefaultValue".
string sqlMatchedData = "SELECT colA, colB, colC, colD " +
"FROM TB_LOOKUP_COLUMN "
ds = databaseManager.GetData(sqlMatchedData);
dataGridView1.ColumnCount = 4;
dataGridView1.Columns[0].Name = "First";
dataGridView1.Columns[1].Name = "Second";
dataGridView1.Columns[2].Name = "Third";
dataGridView1.Columns[3].Name = "Forth";
foreach(DataRow row in ds.Tables[0].Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = row[0].ToString();
dataGridView1.Rows[n].Cells[2].Value = row[3].ToString();
string columnDestination = row[1].ToString();
string columnType = row[2].ToString();
comboboxDestinationColumn(columnDefaultValue);
}
How can I create combobox using the datatable and bind it to the specific cell?
private void comboboxDestinationColumn(string columnDefaultValue)
{
string sqlLookupColumn = "SELECT colALookUp, colBLookUp FROM TB_LOOKUP_COLUMN";
DataSet dsColumn = databaseManager.GetData(sqlLookupColumn);
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Destination";
combo.Name = "combo";
foreach(DataRow row in dsColumn.Tables[0].Rows)
{
//populate combobox with data from datatable with defaul value columnDefaultValue
}
}
EDITED
I have found the way to add the combobox to datagridview. But i still lacking the way on how can i set the default value for each combobox based on the variable columnDefaultValue
private void comboboxDestinationColumn(string columnDefaultValue, int n)
{
string sqlLookupColumn = "SELECT colALookUp, colBLookUp FROM TB_LOOKUP_COLUMN";
DataSet dsColumn = databaseManager.GetData(sqlLookupColumn);
DataGridViewComboBoxCell comboboxColumn = new DataGridViewComboBoxCell();
foreach (DataRow row in dsColumn.Tables[0].Rows)
{
comboboxColumn.Items.Add(row[1].ToString());
}
dataGridView1.Rows[n].Cells[1] = comboboxColumn;
}
I'm trying to find something like:
comboboxColumn.Selected = true;
What is the proper way to do this?
You couls just set a value of your comboboxcell after creating it. Like after the foreach loop, you should just put comboboxColumn.Value = comboboxColumn.Items[0] //or whichever of all the items you want. That would give your combobox the wanted value.
P.S.: It's a bad practic to name a DataGridViewComboBoxCell like "comboboxColumn"...

How can I select a row in 2 DataGridViews when selected in a third DataGridView?

I have 3 DataGridViews.
With DataGridView1 and DataGridView2 you can select rows.
After pushing a button the rows from DataGridView1 and DataGridView2 are compared and every row that has the same values are set in DataGridView3.
What I want is when you select a row in DataGridView3, the same rows are selected in DataGridView1 and DataGridView2.
The code I have, and also works is:
private int ShowSelected(int selectedId, Boolean sBool)
{
DataTable dt = DataGridView1.DataSource;
if(!sBool)
currentGrid = DataGridView1;
int indexCounter = 0;
foreach (DataRow dr in dt.Rows)
{
int cellIdDgv = Convert.ToInt32(dr["cellId"]);
if (selectedId == cellIdDgv)
{
if (sBool)
{
DataGridView1.Rows[indexCounter].Selected = true;
DataGridView1.FirstDisplayedCell = DataGridView1.Rows[indexCounter].Cells[0];
}
else
{
DataGridView2.Rows[indexCounter].Selected = true;
DataGridView2.FirstDisplayedCell = DataGridView2.Rows[indexCounter].Cells[0];
}
}
indexCounter++;
}
}
But what I want is something like this, so you don't have to loop through the whole Grid:
string selection = "cellId = " + selectedId;
DataRow[] drResult = dt.Select(selection);
int rowId = drResult.RowId;
if (sBool)
{
DataGridView1.Rows[rowId].Selected = true;
DataGridView1.FirstDisplayedCell = DataGridView1.Rows[rowId].Cells[0];
}
else
{
DataGridView2.Rows[rowId].Selected = true;
DataGridView2.FirstDisplayedCell = DataGridView2.Rows[rowId].Cells[0];
}
How can I make this work?
To extend on my comment and to provide a local (stackoverflow) solution:
Filtering is accomplished using the BindingSource.Filter property. The example provided on MSDN is:
private void PopulateDataViewAndFilter()
{
DataSet set1 = new DataSet();
// Some xml data to populate the DataSet with.
string musicXml =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<music>" +
"<recording><artist>Coldplay</artist><cd>X&Y</cd></recording>" +
"<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" +
"<recording><artist>Dave Matthews</artist><cd>Live at Red Rocks</cd></recording>" +
"<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" +
"<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" +
"</music>";
// Read the xml.
StringReader reader = new StringReader(musicXml);
set1.ReadXml(reader);
// Get a DataView of the table contained in the dataset.
DataTableCollection tables = set1.Tables;
DataView view1 = new DataView(tables[0]);
// Create a DataGridView control and add it to the form.
DataGridView datagridview1 = new DataGridView();
datagridview1.AutoGenerateColumns = true;
this.Controls.Add(datagridview1);
// Create a BindingSource and set its DataSource property to
// the DataView.
BindingSource source1 = new BindingSource();
source1.DataSource = view1;
// Set the data source for the DataGridView.
datagridview1.DataSource = source1;
//The Filter string can include Boolean expressions.
source1.Filter = "artist = 'Dave Matthews' OR cd = 'Tigerlily'";
}
To make it easier, you may want to create a FilterBuilder.
Edit: To avoid filtering or the above looping mentioned in your question, create a DataTable using a BindingSource etc. which is linked to your `DataGridView1 then:
DataTable DT; // Obtained from the relevent DGV.
DataView view = new DataView(DT);
DataView thisDV = new DataView();
// Then you can use...
thisDV.Find(thisOrThat);
thisDV.FindRows(thisOrThat);
To find the relevant rows in the data, this can then be used to feed a Selection() in you DataGridViews.
I hope this helps.

How to change a DataGridViewTextBoxColumn to a DataGridViewLinkColumn?

I have created a DataGridView and filled it with data from an MS Access database. One of the columns in the database is a hyperlink data type. Instead of it being a DataGridViewLinkColumn in my dataGridView2, it is a DataGridViewTextBoxColumn. Because of this it is displayed as a string and is unusable as a hyperlink. I need to know how to change the type of the column. I've been working on this for a while now and have yet to make any real progress.
This code is in my Form1_Load():
dataGridView2.DataSource = bindingSource2;
GetData2("SELECT ProdName, ProdDesc, PIN, EqVal, AsOf, IssDate, Vendor, Salesperson, OwnerName, InsuredName, Hyperlink FROM ProdInterim WHERE ProdInterim.OwnerID = " + id + "");
The Hyperlink column is the one in question here.
Here is the GetData2():
private void GetData2(string selectCommand)
{
try
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = U:/Syndicate II/Syndicate II.accdb;Persist Security Info = False";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(selectCommand, connectionString);
OleDbCommandBuilder builder = new OleDbCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource2.DataSource = table;
dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}

Categories

Resources