Datagridview with variable columns how? - c#

Im new to C# and want to use a datagridview where the two first colums is the same every time and the rest i dependent of the content of a string list. But how can i do that ?
My code looks like this right now and i can see the failure, but dont know what to do about it :(
Plz help me :)
View.Columns.Clear();
View.AutoGenerateColumns = false;
DataGridViewTextBoxColumn colTime = new DataGridViewTextBoxColumn();
colTime.DataPropertyName = "Time";
colTime.HeaderText = "Time";
colTime.Name = "Time";
colTime.Width = 55;
View.Columns.Add(colTime);
DataGridViewTextBoxColumn colPlace = new DataGridViewTextBoxColumn();
colPlace.DataPropertyName = "Place";
colPlace.HeaderText = "Place";
colPlace.Name = "Place";
colPlace.Width = 55;
View.Columns.Add(colPlace);
for(int i = 0; i < Liste.Length; i++)
{
DataGridViewCheckBoxColumn "Log"+List[i] = new DataGridViewCheckBoxColumn();
"Log"+List[i].DataPropertyName = "List[i]";
"Log"+List[i].HeaderText = "List[i]";
"Log"+List[i].Name = "List[i]";
"Log"+List[i].Width = 55;
View.Columns.Add("Log"+List[i]);
}
Thanks in advance

you can use this function for creating typical DataGridView automatically,
DataGridView CreateDataGridDynamically(int NumberOfCol)
{
DataGridView D = new DataGridView();
for (int i = 0; i < NumberOfCol; i++)
{
DataGridViewTextBoxColumn C1 = new DataGridViewTextBoxColumn();
C1.HeaderText = "Something";
D.Columns.Add(C1);
}
return D;
}
and with datagridview.Rows.Add() and the forth overload, you can simply add some rows with your constraint:
DataGridView D = CreateDataGridDynamically(3);
D.Rows.Add("Sth1", "Sth1", "Sth3");
D.Rows.Add("Sth1", "Sth1", "Sth3");
D.Rows.Add("Sth1", "Sth1", "Sth3");
Controls.Add(D);

Related

How to Set Value in DataGridViewTextBoxCell in WindowForm c#

I can't set Value in DataGridViewTextBox
Here is my code
DataGridViewTextBoxColumn tbCol = new DataGridViewTextBoxColumn();
DataGridViewTextBoxCell tbCell = new DataGridViewTextBoxCell();
tbCell.Value = "1";
tbCol.CellTemplate = tbCell;
tbCol.Name = "qtySelect";
tbCol.HeaderText = "เลือกจำนวน";
gridProduct.Columns.Add(tbCol);
When I Run Textbox are added but it's a blank textbox
any one can help me.
Thank.
You should do this:
yourdatagridview["columnName", rowindex].Value = "Your value";
DataGridViewTextBoxColumn tbCol = new DataGridViewTextBoxColumn();
DataGridViewTextBoxCell tbCell = new DataGridViewTextBoxCell();
// Used for the appearence of the cell, it doesn't mean that there is a correlation between the cell and the column (see below ***)
tbCell.Style.ForeColor = Color.Blue;
tbCol.CellTemplate = tbCell;
tbCol.Name = "qtySelect";
tbCol.HeaderText = "Header";
int colIndex = gridProduct.Columns.Add(tbCol);
const int rowNumber = 0; // define which row you want
//Pay attention that you may need to add rows before writting to the cell
//const int rowNumber = 1;
//gridProduct.Rows.Add();
gridProduct.Rows[rowNumber].Cells[colIndex].Value = "Value for cell";
//*** If you want to work with the cell itself, you first need to get a reference to it
//tbCell = gridProduct.Rows[0].Cells[0] as DataGridViewTextBoxCell;
//tbCell.Value = "1"; // and then you can overwrite the value

Putting a listbox/dropdown menu in a data grid view C#

I have a data table in a data grid view. I want to put an listbox/dropdown menu in a specific column and row. I have tried this but it doesn't work --
var column = new DataGridViewComboBoxColumn();
RunTimeCreatedDataGridView[1, 1].Value = RunTimeCreatedDataGridView.Columns.Add(column);
Here is how I populate the table--
public DataTable createGridForForm(int rows, int columns)
{
// Create the output table.
DataTable table = new DataTable();
for (int i = 1; i <= columns; i++)
{
table.Columns.Add("column " + i.ToString());
}
for (int i = 1; i < rows; i++)
{
DataRow dr = table.NewRow();
// populate data row with values here
ListBox test = new ListBox();
myTabPage.Controls.Add(test);
table.Rows.Add(dr);
}
return table;
}
And here is how I create the datagridview.
private void createGridInForm(int rows, int columns)
{
DataGridView RunTimeCreatedDataGridView = new DataGridView();
RunTimeCreatedDataGridView.DataSource = createGridForForm(rows, columns);
//DataGridViewColumn ID_Column = RunTimeCreatedDataGridView.Columns[0];
//ID_Column.Width = 200;
int positionForTable = getLocationForTable();
RunTimeCreatedDataGridView.BackgroundColor = Color.WhiteSmoke;
RunTimeCreatedDataGridView.Size = new Size(995, 200);
RunTimeCreatedDataGridView.Location = new Point(5, positionForTable);
myTabPage.Controls.Add(RunTimeCreatedDataGridView);
}
You were right on track with your first code block... the problem was you were trying to add a column to a cell reference. If you want to add a column where all rows have a drop down, then do exactly what you were doing, but simply add the column instead of specifying a cell value, like this:
var column = new DataGridViewComboBoxColumn();
RunTimeCreatedDataGridView.Columns.Add(column);
Then, specify the datasource as you normally would for a combobox.
Alternatively, if you want a specific cell to have a different combobox, or only a single cell in the column to have one, you can create a separate one as shown here or here.
Edit: To add a combobox to a specific cell in the DataGridView, you would do something like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridView dgv = new DataGridView();
// add some columns and rows
for (int i = 0; i < 10; i++)
{
DataGridViewCell c = new DataGridViewHeaderCell();
dgv.Columns.Add("Column" + i, Convert.ToString(i));
}
for (int i = 0; i < 10; i++)
{
dgv.Rows.Add(new DataGridViewRow());
}
//create a new DataGridViewComboBoxCell and give it a datasource
var DGVComboBox = new DataGridViewComboBoxCell();
DGVComboBox.DataSource = new List<string> {"one", "two", "three"};
DGVComboBox.Value = "one"; // set default value of the combobox
// add it to cell[4,4] of the DataGridView
dgv[4, 4] = DGVComboBox;
// add the DataGridView to the form
this.Controls.Add(dgv);
}
}

how to represent in datagridview?

I have a class that I did all calculation in it and now I want to represent this data in datagridview what should I do using c#?
that what I did but it didn't work
for (int i = 1; i <= cust_num; i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells["Customer_Number"].Value = cust_num.ToString();
dataGridView1.Rows[i].Cells["Time_between_Arrival"].Value = inter_Arrival_time.ToString();
dataGridView1.Rows[i].Cells["service_Time"].Value = service_Time.ToString();
dataGridView1.Rows[i].Cells["Arrival_Time"].Value = rand_inter_Arrival.ToString();
dataGridView1.Rows[i].Cells["Time_Service_Beg"].Value = Arrival_Time.ToString();
dataGridView1.Rows[i].Cells["ServiceNum"].Value = service_number.ToString();
dataGridView1.Rows[i].Cells["service_Time"].Value = rand_service_time.ToString();
dataGridView1.Rows[i].Cells["Time_service_End"].Value = finsh_time.ToString();
dataGridView1.Rows[i].Cells["Waiting_Time"].Value = waiting_time.ToString();
// dataGridView1.Rows.Add(row);
}
string[] row = new string[] { cust_num.ToString(), inter_Arrival_time.ToString(), ...... };
dataGridView1.Rows.Add(row);
You can add row to datagridview like this

want to assign datacolumn with checkbox type to a gridview

i have a datagridview and want to add DataGridViewCheckBoxColumn
otherwise i have a datatable and want to set it as datasource of my gridview
but cant show my gridview with check box
for (int i = 0; i < oldTable.Rows.Count; i++)
{
DataColumn newHeader = new DataColumn();
newHeader.ColumnName = oldTable.Rows[i].ItemArray[3].ToString();
newHeader.DataType =typeof(DataGridViewCheckBoxColumn);
//newHeader.DataType = new DataGridViewCheckBoxColumn();
//string newHeader = oldTable.Rows[i].ItemArray[3].ToString();
newTable.Columns.Add(newHeader);
}
DataRow accessRow = newTable.NewRow();
for (int j = 0; j < oldTable.Rows.Count; j++)
{
Boolean access =Convert.ToBoolean(oldTable.Rows[j][2]);
accessRow[j] = access;
var sklj= accessRow[j].GetType();
}
newTable.Rows.Add(accessRow);
dataGridView1.DataSource = newTable;
I think this is simpler than that:
EDIT: I was mistaken: This should do it:
DataGridViewCheckBoxColumn dgchk = new DataGridViewCheckBoxColumn();
dataGridView1.Columns.Add(dgchk);
this should be done after you set the DataSource.
Change your code like this:
for (int i = 0; i < oldTable.Rows.Count; i++)
{
DataColumn newHeader = new DataColumn();
newHeader.ColumnName = oldTable.Rows[i].ItemArray[3].ToString();
newHeader.DataType =typeof(System.Boolean); //Change This Line Like This
newTable.Columns.Add(newHeader);
}
Change your code typeof(DataGridViewCheckBoxColumn()) to typeof(System.Boolean)
Just add new Column and Row like this...
yourTable.Columns.Add(new DataColumn("Selected", typeof(bool)));
yourTable.Rows.Add(false)

DataGridView not showing values in runtime created columns

I´m having a really wierd issue. I assign to my DataGridView a list of entities as a DataSource. I create some columns in runtime, and then, for each Row in the DataGridView, I complete the values of that new columns base on some values of some columns of the row.
The code works fine, because I´m displaying that same DataGridView in other forms. But in this new UserControl, it seems that it´s not showing any values on that new columns.
The wierd thing, is that the values are actually there, because when I do the foreach row loop, I have some acumulators int objects that shows the values in a textbox, and the values are correct.
I used a try and catch to see if something was wrong, but everything is fine.
I attached an image of what I´m getting.
Those two highlighted textboxes are the one that acummulates the values of those two columns..
As I said, the same code is working fine in other forms. Just in case, this UserControl is added to a panel in a form.
This is the code I use for the DataGridView:
public void Actualizar_grilla_prestamos()
{
dgv_Prestamos.DataSource = null;
dgv_Prestamos.Columns.Clear();
dgv_Prestamos.DataSource = lista_prestamos;
dgv_Prestamos.RowHeadersVisible = false;
//Agregar columna cuotas restantes
DataGridViewColumn cuotas_restantes = new DataGridViewColumn();
{
cuotas_restantes.HeaderText = "C. Rest.";
cuotas_restantes.Name = "cuotas_restantes";
cuotas_restantes.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
cuotas_restantes.CellTemplate = new DataGridViewTextBoxCell();
cuotas_restantes.ToolTipText = "Cantidad de cuotas restantes por cobrar";
}
dgv_Prestamos.Columns.Add(cuotas_restantes);
//Agregar columna tipo de tasa
DataGridViewColumn tipo_tasa = new DataGridViewColumn();
{
tipo_tasa.HeaderText = "Tipo tasa";
tipo_tasa.Name = "tipo_tasa";
tipo_tasa.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
tipo_tasa.CellTemplate = new DataGridViewTextBoxCell();
}
dgv_Prestamos.Columns.Add(tipo_tasa);
//Agregar columna garantes
DataGridViewColumn garantes = new DataGridViewColumn();
{
garantes.HeaderText = "Garantes";
garantes.Name = "garantes";
garantes.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
garantes.CellTemplate = new DataGridViewTextBoxCell();
}
dgv_Prestamos.Columns.Add(garantes);
dgv_Prestamos.Columns["garantes"].DisplayIndex = dgv_Prestamos.Columns["Cliente1"].Index;
//Agregar columna cuotas mora
DataGridViewColumn cuotas_mora = new DataGridViewColumn();
{
cuotas_mora.HeaderText = "C. Venc.";
cuotas_mora.Name = "cuotas_mora";
cuotas_mora.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
cuotas_mora.CellTemplate = new DataGridViewTextBoxCell();
cuotas_mora.ToolTipText = "Cantidad de cuotas vencidas";
}
dgv_Prestamos.Columns.Add(cuotas_mora);
int cant_total_cuotas_mora = 0;
int total_cuotas_restantes = 0;
foreach (DataGridViewRow r in dgv_Prestamos.Rows)
{
Estado_prestamo estado = (Estado_prestamo)dgv_Prestamos.Rows[r.Index].Cells["Estado_prestamo"].Value;
if (estado.id_estado_prestamo != 3)
{
var lista_cuotas = (System.Data.Objects.DataClasses.EntityCollection<Sistema_financiero.Cuota>)dgv_Prestamos.Rows[r.Index].Cells["Cuota"].Value;
dgv_Prestamos.Rows[r.Index].Cells["cuotas_mora"].Value = lista_cuotas.Where(x => x.pagada != true && x.fecha_vencimiento < DateTime.Now.Date).Count();
if (Convert.ToInt32(dgv_Prestamos.Rows[r.Index].Cells["cuotas_mora"].Value) > 0)
{
dgv_Prestamos.Rows[r.Index].Cells["cuotas_mora"].Style.ForeColor = Color.Red;
}
dgv_Prestamos.Rows[r.Index].Cells["cuotas_restantes"].Value = lista_cuotas.Where(x => x.pagada != true).Count();
}
else
{
dgv_Prestamos.Rows[r.Index].Cells["cuotas_mora"].Value = 0;
dgv_Prestamos.Rows[r.Index].Cells["cuotas_restantes"].Value = 0;
dgv_Prestamos.Rows[r.Index].Cells["cuotas_restantes"].Style.ForeColor = Color.Green;
}
if (Convert.ToBoolean(dgv_Prestamos.Rows[r.Index].Cells["tasa_fija"].Value) == true)
{
dgv_Prestamos.Rows[r.Index].Cells["tipo_tasa"].Value = "FIJA";
}
else
{
dgv_Prestamos.Rows[r.Index].Cells["tipo_tasa"].Value = "VARIABLE";
}
dgv_Prestamos.Rows[r.Index].Cells["garantes"].Value = ((System.Data.Objects.DataClasses.EntityCollection<Sistema_financiero.Cliente>)dgv_Prestamos.Rows[r.Index].Cells["Cliente1"].Value).Count;
cant_total_cuotas_mora = cant_total_cuotas_mora + Convert.ToInt32(dgv_Prestamos.Rows[r.Index].Cells["cuotas_mora"].Value);
total_cuotas_restantes = total_cuotas_restantes + Convert.ToInt32(dgv_Prestamos.Rows[r.Index].Cells["cuotas_restantes"].Value);
}
tbx_Cuotas_adeudadas_vencidas.Text = cant_total_cuotas_mora.ToString();
tbx_Total_cuotas_restantes.Text = total_cuotas_restantes.ToString();
//Agregar columna ver prestamo
DataGridViewImageColumn ver_prestamo = new DataGridViewImageColumn();
{
ver_prestamo.HeaderText = "";
ver_prestamo.Name = "ver_prestamo";
ver_prestamo.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
ver_prestamo.CellTemplate = new DataGridViewImageCell();
ver_prestamo.Image = Properties.Resources.eye_small_grid;
ver_prestamo.ToolTipText = "Ver préstamo";
}
dgv_Prestamos.Columns.Add(ver_prestamo);
dgv_Prestamos.Columns["ver_prestamo"].DisplayIndex = 0;
dgv_Prestamos.Columns["id_prestamo"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dgv_Prestamos.Columns["num_cuotas"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dgv_Prestamos.Columns["cuotas_mora"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dgv_Prestamos.Columns["cuotas_restantes"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dgv_Prestamos.Columns["importe"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dgv_Prestamos.Columns["Moneda"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dgv_Prestamos.Columns["Sistema_amortizacion"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dgv_Prestamos.Columns["cuotas_mora"].DisplayIndex = dgv_Prestamos.Columns["num_cuotas"].Index + 1;
dgv_Prestamos.Columns["cuotas_restantes"].DisplayIndex = dgv_Prestamos.Columns["num_cuotas"].Index + 1;
dgv_Prestamos.Columns["importe"].DisplayIndex = dgv_Prestamos.Columns["garantes"].DisplayIndex;
dgv_Prestamos.Columns["num_cuotas"].DisplayIndex = dgv_Prestamos.Columns["cuotas_restantes"].DisplayIndex;
dgv_Prestamos.Columns["Estado_prestamo"].DisplayIndex = dgv_Prestamos.Columns[dgv_Prestamos.Columns.Count - 1].Index;
dgv_Prestamos.Columns["Moneda"].DisplayIndex = dgv_Prestamos.Columns[dgv_Prestamos.Columns.Count - 2].Index;
dgv_Prestamos.Columns["tipo_tasa"].DisplayIndex = dgv_Prestamos.Columns["tasa_fija"].Index;
List<int> lista_columnas_visibles = new List<int> { dgv_Prestamos.Columns["Estado_prestamo"].Index, dgv_Prestamos.Columns["garantes"].Index, dgv_Prestamos.Columns["importe"].Index, dgv_Prestamos.Columns["Sistema_amortizacion"].Index, dgv_Prestamos.Columns["tipo_tasa"].Index, dgv_Prestamos.Columns["Moneda"].Index, dgv_Prestamos.Columns["id_prestamo"].Index, dgv_Prestamos.Columns["num_cuotas"].Index, dgv_Prestamos.Columns["cuotas_mora"].Index, dgv_Prestamos.Columns["cuotas_restantes"].Index, dgv_Prestamos.Columns["ver_prestamo"].Index };
Mostrar_ocultar_columnas(dgv_Prestamos, lista_columnas_visibles);
dgv_Prestamos.Columns["num_cuotas"].HeaderText = "Cuotas";
dgv_Prestamos.Columns["id_prestamo"].HeaderText = "Nº";
dgv_Prestamos.Columns["tasa_fija"].HeaderText = "Tipo tasa";
dgv_Prestamos.Columns["importe"].HeaderText = "Importe";
dgv_Prestamos.Columns["Estado_prestamo"].HeaderText = "Estado";
dgv_Prestamos.Columns["Sistema_amortizacion"].HeaderText = "Amortización";
dgv_Prestamos.Columns["importe"].DefaultCellStyle.Format = String.Format("$ ##0.##");
if (dgv_Prestamos.Columns["Moneda"].Width > 99)
{
dgv_Prestamos.Columns["Moneda"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
dgv_Prestamos.Columns["Moneda"].Width = 99;
}
}
You can see that the DataGridView has a column with an eye. If you click the eye, you can see that entity in another form. If you change the entity state in that form, it returns a value (borrado) with true if changes has been made, or false if no change has been made.
If changes were detected, then I call the above method again. Magically, it shows all that missing values!
private void dgv_Prestamos_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1)
{
if (e.ColumnIndex == dgv_Prestamos.Columns["ver_prestamo"].Index)
{
frm_Ver_Prestamo ver_prestamo = new frm_Ver_Prestamo();
ver_prestamo.prestamo_seleccionado = (Prestamo)dgv_Prestamos.Rows[e.RowIndex].DataBoundItem;
ver_prestamo.db = db;
ver_prestamo.ShowDialog();
if (ver_prestamo.borrado == true)
{
dgv_Prestamos.DataSource = null;
Cursor.Current = Cursors.WaitCursor;
Actualizar_grilla_prestamos();
Cursor.Current = Cursors.Default;
}
}
}
}
ver_prestamo is the form that shows the entity. I don´t know what make that work, the only difference is that I do a DataSource = null before. But I do that in the method anyways..
Have you tried moving the dgv_Prestamos.DataSource = lista_prestamos; to the bottom of Actualizar_grilla_prestamos.
I think that it is doing the binding when you set the datasource and can't see the columns you have created afterward.
"Construct the grid, set the DataSource, then change the appearances in the DataBindingComplete event." - glace

Categories