Cannot set DataGrid row header value - c#

I'm having difficulty setting the header value for DataGrid rows.
My DataGrid is bounded to DataTable but the following code won't display the row's header for the first row. Any ideas?
Note: RowHeadersVisible = True
(Assume that my DataTable has at least 1 col and 1 row before reaching this code)
public new void ShowDialog()
{
dataGridView_replaceTable.Columns.Clear();
dataGridView_replaceTable.Rows.Clear();
dataGridView_replaceTable.DataSource = getDataTable(); <-- returns DataTable
dataGridView_replaceTable.Rows[0].HeaderCell.Value = "ROW HEADER 1";
// I expect to see the this string in the first row header - but it remians empty!
}
The code for adding rows and columns to the DataTable:
we have:
replaceTableValues DataTable
as class property.
public void addCol()
{
DataColumn column;
column = new DataColumn(string colName);
column.DataType = System.Type.GetType("System.String");
column.ColumnName = colName;
column.ReadOnly = false;
replaceTableValues.Columns.Add(column);
}
public void addRow()
{
DataRow row;
row = replaceTableValues.NewRow();
string[] arr = new string[numOfCols+1];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = ""; // fill row data as empty string
}
try
{
replaceTableValues.Rows.Add(arr);
}
catch (System.Exception ex)
{
updateReplaceVarErrorMsg(TABLE_EXCEPTION);
}
}
What i'm trying to achieve: (red text)
Image
Thanks.

You should use HeaderText property of Columns collection instead:
dataGridView_replaceTable.Columns[0].HeaderText="ROW HEADER 1";
You could also do this when you add your columns by using Caption property:
public void addCol()
{
DataColumn column;
column = new DataColumn(string colName);
column.DataType = System.Type.GetType("System.String");
column.ColumnName = colName;
column.Caption = "My header" // ASSIGN HEADERS HERE
column.ReadOnly = false;
replaceTableValues.Columns.Add(column);
}

grid.Columns[0].HeaderText = "Something special";
A basic way to add a column is:
int columnIndex = grid.Columns.Add("columnName", "Header Text");

Related

DataGridViewComboBoxColumn not showing DataSource

My code:
private void InitGrid(DataTable dataTable, ref DataGridView grid, bool resetColumns)
{
if (grid.Columns.Count > 0)
{
if (resetColumns)
{
grid.Columns.Clear();
grid.DataSource = null;
}
else
{
return;
}
}
DataGridViewColumn column;
grid.AutoGenerateColumns = false;
// apply entire data from table to grid.
grid.DataSource = dataTable;
// set column properties according to their type (combo, text, etc.)
foreach (DataColumn col in dataTable.Columns)
{
if (m_ColumnTypes[col.ColumnName].Equals("COMBO"))
{
// get query number to load specific column's data
string adminQuery = Server.LoadData("633", new List<string>() { col.ColumnName, m_TableFullName }).Rows[0][0].ToString();
column = new DataGridViewComboBoxColumn();
string queryParam = Controller.MainController.User;
switch (col.ColumnName.ToUpper())
{
case "FIELD1NAME":
(column as DataGridViewComboBoxColumn).DisplayMember = col.ColumnName;
(column as DataGridViewComboBoxColumn).ValueMember = "field1id";
break;
case "FIELD2NAME":
(column as DataGridViewComboBoxColumn).DisplayMember = col.ColumnName;
(column as DataGridViewComboBoxColumn).ValueMember = "field2id";
queryParam = string.Concat("select column_value from table(fn_mgr_workspaces('", Controller.MainController.User, "'))");
break;
case "PRIORITY":
(column as DataGridViewComboBoxColumn).DisplayMember = col.ColumnName;
(column as DataGridViewComboBoxColumn).ValueMember = col.ColumnName;
queryParam = "10";
break;
}
(column as DataGridViewComboBoxColumn).DataSource = Server.LoadData(adminQuery, new List<string>() { queryParam });
}
else
{
column = new DataGridViewTextBoxColumn() { AutoSizeMode = m_ColumnTypes[col.ColumnName].Equals("TAGS") ? DataGridViewAutoSizeColumnMode.Fill : DataGridViewAutoSizeColumnMode.AllCells, ReadOnly = true };
}
column.Name = col.ColumnName.ToUpper();
column.HeaderText = m_ColumnNameTranslations[col.ColumnName.ToUpper()];
column.DataPropertyName = column is DataGridViewComboBoxColumn ? (column as DataGridViewComboBoxColumn).ValueMember : col.ColumnName;
grid.Columns.Add(column);
}
// after setting columns. going over every row and trying to filter out the datasource of field2. this is where my problem is
foreach (DataGridViewRow dgvr in grid.Rows)
{
if (!dgvr.IsNewRow)
{
string wsId = dgvr.Cells["filed1id"].Value.ToString();
DataTable filteredData = ((dgvr.Cells["field2name"] as DataGridViewComboBoxCell).DataSource as DataTable).Select("thefieldname = " + wsId).CopyToDataTable();
DataView dv = filteredData.DefaultView;
dv.Sort = "field2name";
(dgvr.Cells["field2name"] as DataGridViewComboBoxCell).DataSource = null;
(dgvr.Cells["field2name"] as DataGridViewComboBoxCell).DisplayMember = "field2name";
(dgvr.Cells["field2name"] as DataGridViewComboBoxCell).ValueMember = "field2id";
(dgvr.Cells["field2name"] as DataGridViewComboBoxCell).DataSource = dv.ToTable();
}
}
}
(field names and some object names were scrambled for security purposes)
My problem:
The DataSource of field2 which is a ComboboxColumn does not change. It always shows me the entire data and not the filtered data that I try to set for it.
Even though I nullify it and re-set it to the filtered data, it doesn't work.
What I'm trying to achieve is that the DataSource in field2 column should be dependant on the data of field1 for each row of the grid.
I tried setting the datasource for the other columns and not setting it for field2 and then after that going over every row and setting the filtered datasource on field2 but it comes up completely empty as if the datasource set for every row hasn't worked at all.
I'm doing something wrong. How the hell do I do this?
The EditControlShowing event on the DataGridView will allow you to accomplish this.
Add an event handler to this method.
private void grid_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if ( grid.CurrentCell.ColumnIndex == dgvr.Columns["field2name"].Index )
{
// Get Combobox
ComboBox combo = e.Control as ComboBox;
// Get Other Column's Value
string wsId = grid.Rows[grid.CurrentCell.RowIndex].Cells["filed1id"].Value.ToString();
// Get Filtered Data Based Off Of Other Column's Value
DataTable filteredData = (combo.DataSource as DataTable).Select("thefieldname = " + wsId).CopyToDataTable();
DataView dv = filteredData.DefaultView;
dv.Sort = "field2name";
// Rebind
combo.DataSource = null;
combo.DisplayMember = "field2name";
combo.ValueMember = "field2id";
combo.DataSource = dv.ToTable();
}
}

datagridview not showing all columns when adding columns

I have datagridview column from database FullName and then I add columns manually from code the position 1 to 5 so I added 5 columns. I can't get all the rows and columns when I tried to get in DataTable at the end.
DataTable table = database.Execute("Select FirstName + ' ' + LastName as FullName from People");
dataGridView1.DataSource = table;
for (int i = 1; i <= 5 ; i++)
{
dataGridView1.Columns.Add(new DataGridViewColumn()
{
HeaderText = i.ToString(),
CellTemplate = new DataGridViewTextBoxCell(),
Width = 30
}
);
}
DataTable dt = new DataTable();
dt = dataGridView1.DataSource as DataTable;
Alright, the issue here is that you are manually adding columns to your DataGridView, which has a separate collection of columns than your DataSource. When you get the DataTable from your dataGridView1.DataSource, you are getting just the "FullName" column from the original query that you performed (because the collection of columns in that DataTable still only contains just the one column).
To fix this, add this line to your for loop:
(dataGridView1.DataSource as DataTable).Columns.Add(i.ToString());
Another note, you can just do:
DataTable dt = dataGridView1.DataSource as DataTable;
instead of:
DataTable dt = new DataTable(); // Don't need to create empty DataTable here
dt = dataGridView1.DataSource as DataTable;
This will keep you from unnecessarily allocating memory.
Well...
If the Cory's solution does not work for you try to add columns within
BeginInvoke((Action)(() =>
{
// for example
var Code = new DataGridViewTextBoxColumn()
{
Width = 50,
DataPropertyName = "Code",
DefaultCellStyle = new DataGridViewCellStyle()
{
Alignment = DataGridViewContentAlignment.MiddleLeft,
ForeColor = Color.Black,
},
HeaderCell = new DataGridViewColumnHeaderCell()
{
Style = new DataGridViewCellStyle()
{
Alignment = DataGridViewContentAlignment.MiddleCenter,
}
}
};
Code.HeaderText = "Code";
dgvWorkTypes.Columns.Add(Code);
}));

How to add textBox to Winform dataGridView cells

I want to add textBox to my column cells by for loop...
My code:
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("No");
dt.Columns.Add(dc);
dc = new DataColumn("Item");
dt.Columns.Add(dc);
dc = new DataColumn("Available Stock");
dt.Columns.Add(dc);
dc = new DataColumn("Quantity");
dt.Columns.Add(dc);
dc = new DataColumn("Price");
dt.Columns.Add(dc);
// Define rows
for (int i = 0; i < count; i++)
{
string no = dtr.Rows[i][0].ToString();
string item = dtr.Rows[i][2].ToString() + " " + dtr.Rows[i][1].ToString();
string A_qty = dtr.Rows[i][3].ToString();
string price = dtr.Rows[i][4].ToString();
dt.Rows.Add(no, item, A_qty,"[i want to add text box here] " ,price);
}
dataGridView1.DataSource = dt;
I want to add textBoxes to 4th column and I want access that one by one.
You can add textBox column to DataGridView instead and loop through DataGridView like
DataTable dt=new DataTable();
dt.Columns.Add("No",typeof(int));
dt.Columns.Add("Item",typeof(string));
dt.Columns.Add("quantity",typeof(int));
dt.Columns.Add("Price",typeof(decimal));
//Add row to the datatable
for (int i = 0; i < count; i++)
{
//Not Sure what dtr is you looping through
string no = dtr.Rows[i][0].ToString();
string item = dtr.Rows[i][1].ToString() + " " + dtr.Rows[i][1].ToString();
string A_qty = dtr.Rows[i][2].ToString();
string price = dtr.Rows[i][3].ToString();
dt.Rows.Add(no, item, A_qty, price);
}
//Create New DataGridViewTextBoxColumn
DataGridViewTextBoxColumn textboxColumn=new DataGridViewTextBoxColumn();
//Bind DataGridView to Datasource
dataGridView1.datasource=dt;
//Add TextBoxColumn dynamically to DataGridView
dataGridView1.Columns.Add(textboxColumn);
//Loop through DataGridView
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//Do your task here
string fourthColumn = row.Cells[4].Value.toString();
}
Not sure. But hope this code will help you. Just add column of type textbox to your datatable.
DataTable table = new DataTable();
DataColumn col = new DataColumn("Name", typeof(TextBoxBase));
table.Columns.Add(col);

How to add New Column with Value to the Existing DataTable?

I have One DataTable with 5 Columns and 10 Rows.
Now I want to add one New Column to the DataTable and I want to assign DropDownList value to the New Column.
So the DropDownList value should be added 10 times to the New Column.
How to do this?
Note: Without using FOR LOOP.
For Example: My Existing DataTable is like this.
ID Value
----- -------
1 100
2 150
Now I want to add one New Column "CourseID" to this DataTable.
I have One DropDownList. Its selected value is 1.
So My Existing Table should be like below:
ID Value CourseID
----- ------ ----------
1 100 1
2 150 1
How to do this?
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
Add the column and update all rows in the DataTable, for example:
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
DataRow row = tbl.NewRow();
row["ID"] = i;
row["Name"] = i + ". row";
tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;
//Data Table
protected DataTable tblDynamic
{
get
{
return (DataTable)ViewState["tblDynamic"];
}
set
{
ViewState["tblDynamic"] = value;
}
}
//DynamicReport_GetUserType() function for getting data from DB
System.Data.DataSet ds = manage.DynamicReport_GetUserType();
tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]
for (int i = 0; i < tblDynamic.Rows.Count; i++)
{
if (tblDynamic.Rows[i]["Type"].ToString()=="A")
{
tblDynamic.Rows[i]["TypeName"] = "Apple";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "B")
{
tblDynamic.Rows[i]["TypeName"] = "Ball";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "C")
{
tblDynamic.Rows[i]["TypeName"] = "Cat";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "D")
{
tblDynamic.Rows[i]["TypeName"] = "Dog;
}
}

How to check if a record is already present in the DataView? C#

I have a DataView which has two columns: ContactID, and Name
How can I check if a particular ContactID is already existing in the DataView?
Have you had a look at DataView.FindRows Method or maybe DataView.Find Method
The DataView has a method called FindRows, this can be used to search for a specific contactID, for example...
var table = new DataTable();
var column = new DataColumn("Id", typeof (int));
table.Columns.Add(column);
table.PrimaryKey = new[] {column}; // Unique Constraint
var row = table.NewRow();
row["Id"] = 100;
table.Rows.Add(row);
row = table.NewRow();
row["Id"] = 200;
table.Rows.Add(row);
var view = new DataView(table) { ApplyDefaultSort = true };
var rows = view.FindRows(200);
foreach(var r in rows)
{
Console.WriteLine(r["Id"]);
}
Use the Following code to Find the row in the Dataview
//Your original Table Which consist of Data
DataTable dtProducts = new DataTable();
//Add the DataTable to DataView
DataView ProductDataView = new DataView(dtProducts);
ProductDataView.RowFilter = "";
ProductDataView.Sort = "ProdId";
int recordIndex = -1;
//In the Find Row Method pass the Column
//value which you want to find
recordIndex = ProductDataView.Find(1);
if (recordIndex > -1)
{
Console.WriteLine("Row Found");
}

Categories