Datatable and Datagridview - c#

I have datatable table like
id name address phoneno
1 abc kfjskl 798798
2 bcd kjdsfl 808909
3 899009
fjsh kjllkjl
5 jfkd
And I am displaying this value in the datagridview by code
dataGridView1.ColumnCount = Table.Columns.Count;
dataGridView1.RowCount = Table.Rows.Count;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
dataGridView1[j, i].Value = Table.Rows[i][j].ToString();
}
}
Now I don't want to display row that has some missing value like If I will do that then the datagridview will look like
1 abc kfjskl 798798
2 bcd kjdsfl 808909
How can I do that ?

This will do what you need (I think):
dataGridView1.ColumnCount = Table.Columns.Count;
for (int i = 0; i < Table.Rows.Count; i++)
{
bool valueMissing = false;
DataGridViewRow row = new DataGridViewRow();
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
if (Table.Rows[i][j].ToString() == "")
{
valueMissing = true;
break;
}
else
{
row.Cells[j].Value = Table.Rows[i][j];
}
}
if (!valueMissing)
{
dataGridView1.Rows.Add(row);
}
}
This may need to be modified to check for null values in Table.Rows[i][i] (in addition to just checking for empty string values).

I think your best choice is to use a DataView between the DataGridView and the DataTable.
The DataView allows you to filter values using and expression without affecting to the original DataTable. To filter all empty columns you can create a view with this expression:
DataView view = new DataView(table);
view.RowFilter = "ISNULL(id, '') <> '' AND ISNULL(name, '') <> '' AND ISNULL(address, '') <> '' AND ISNULL(phoneno, '') <> ''";
The ISNULL function replaces a column value whit the specified string, if the column value is null. So the filter is replacing every NULL value with empty strings, so excluding NULL or Empty columns.
Then you can use this view to assing values to the grid, instead of using the datatable:
dataGridView1.ColumnCount = view.Columns.Count;
dataGridView1.RowCount = view.Rows.Count;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
dataGridView1[j, i].Value = view.Rows[i][j].ToString();
}
}
Also instead of using loops to provide values to the grid, you can simply use databinding. It's much simpler:
dataGridView1.DataSource = view;
Hope it helps!

I'm not sure if I understand, but you could possibly use DataTable.Select to filter out any rows with missing values before you insert them in the datagrid.
Or otherwise, instead of using a for loop for the rows, just use a foreach loop on the rows in the table and add the rows one by one with dataGridView.Rows.Add(newRow).

Related

Getting datagridview cell index in C#

How to get Cell index after comparing values, for example i have this
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[value].Value.ToString() == radTextBox1.Text)
{
//If the value matches how to get the row index of that
}
}
This might do the job:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == radTextBox1.Text)
{
dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0];
}
}
If you are wanting to find the value in any cell then you need to use a nested loop.
dataGridView1.ClearSelection();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int c = 0; c < dataGridView1.Columns.Count; c++)
{
if (dataGridView1.Rows[i].Cells[c].Value.ToString() == radtextBox1.Text)
{
dataGridView1.Rows[i].Selected = true;
}
}
}
This will move through each row while checking all the columns for a value and will hilight any row where a cell has that value. Note that this code is case sensitive so "City" <> "city" but that is easily fixed using .ToUpper or .ToLower as needed.
One other thing to add, this code also is based off a DGV that has AllowUserToAddRows set to false. If you need the edit row, you either need to -1 from the count in the rows loops or check to ensure that the current row is false for .IsNewRow.
You found the Row you're looking for.
It's i variable in your code.
var requiredRowIndex = -1;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[value].Value.ToString() == radTextBox1.Text)
{
requiredRowIndex = i;
break;
}
}
if (requiredRowIndex != -1)
{
// It was found.
}
else
{
// It was not found.
}
You dont show us what is the value? It's actualy index of Cell you're looking for.

Transposing columns in GridView

I have a data table that contains the data like below.
I want to display it in my Grid View like Following. It is actually the transpose of above table and one additional Row added for Viewing Product Details that will be a link button.
Can you please help me how can I achieve the following requirement in ASP.net using C#.
Many Thanks,
Awais Afzal.
Assuming that you table is a DataTable, you could use such an extension to reorder it:
public static DataTable Pivot(this DataTable tbl)
{
var tblPivot = new DataTable();
tblPivot.Columns.Add(tbl.Columns[0].ColumnName);
for (int i = 1; i < tbl.Rows.Count; i++)
{
tblPivot.Columns.Add(Convert.ToString(i));
}
for (int col = 0; col < tbl.Columns.Count; col++)
{
var r = tblPivot.NewRow();
r[0] = tbl.Columns[col].ToString();
for (int j = 1; j < tbl.Rows.Count; j++)
r[j] = tbl.Rows[j][col];
tblPivot.Rows.Add(r);
}
return tblPivot;
}
and set it as new DataSource:
dataGridView1.DataSource = oldDataTable.Pivot();

Convert empty cells in a data table to 0

I have a data table that has 1 column having few cells having null value. How can I convert them to 0 ?
I bind this data table to a data grid view and cells are empty in case of null in the data table.I need to have 0 displayed in the datagridview.
Edit your cell template and set the NullValue to 0
Honestly, I'd clear this up before binding to the datagrid. I'd execute a for loop and just change all the DBNull values to 0. Its quick, easy, understandable code. This has the benefit of actually changing the data to 0, instead of changing how it is viewed to 0, as others have suggested by making tweaks to the dataGrid. Either strategy has merits, just depends on what you want to do.
Try this:
for (int i = 0; i < dataTable.Rows.Count; i++)
{
DataRow row = dataTable.Rows[i];
if (row["ColumnA"] == DBNull.Value)
{
row["ColumnA"] = 0;
}
}
I set the property of the DataGridViewTextBox column .Seems to be working as expected.
amountColumn.DefaultCellStyle.NullValue = "0";
If you fetch data to display from database then you might bind null to 0 using following syntax:
SELECT ISNULL(ColumnName, 0)
FROM TableName;
this works for all rows and columns with null or empty values
For i As Integer = 0 To output.Tables(0).Rows.Count - 1
Dim row As DataRow = output.Tables(0).Rows(i)
For j As Integer = 0 To output.Tables(0).Columns.Count - 1
If row(j) Is DBNull.Value Then
row(j) = 0
End If
If row(j).ToString.Length = 0 Then
row(j) = 0
End If
Next
Next
C#
for (int i = 0; i <= output.Tables[0].Rows.Count - 1; i++)
{
DataRow row = output.Tables[0].Rows[i];
for (int j = 0; j <= output.Tables[0].Columns.Count - 1; j++)
{
if (object.ReferenceEquals(row[j], DBNull.Value))
{
row[j] = 0;
}
if (row[j].ToString().Length == 0)
{
row[j] = 0;
}
}
}
Try this:
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
{
dt.Rows[i][j] = "0";
}
}
}

Storing the records in csv file from datatable

I have datatable and I am displaying those values in the datagridview with the helping of code :
dataGridView1.ColumnCount = TableWithOnlyFixedColumns.Columns.Count;
dataGridView1.RowCount = TableWithOnlyFixedColumns.Rows.Count;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
dataGridView1[j, i].Value = TableWithOnlyFixedColumns.Rows[i][j].ToString();
}
}
TableExtractedFromFile.Clear();
TableWithOnlyFixedColumns.Clear();
Now I want to save the records in the datatable in csv file.How can I do that ?
You could do this:
// we'll use these to check for rows with nulls
var columns = yourTable.Columns
.Cast<DataColumn>();
// say the column you want to sort by is called "Date"
var rows = yourTable.Select("", "Date ASC"); // or "Date DESC"
using (var writer = new StreamWriter(yourPath)) {
for (int i = 0; i < rows.Length; i++) {
DataRow row = rows[i];
// check for any null cells
if (columns.Any(column => row.IsNull(column)))
continue;
string[] textCells = row.ItemArray
.Select(cell => cell.ToString()) // may need to pick a text qualifier here
.ToArray();
// check for non-null but EMPTY cells
if (textCells.Any(text => string.IsNullOrEmpty(text)))
continue;
writer.WriteLine(string.Join(",", textCells));
}
}

loop through all rows and columns of a gridview using C#

I have a grid view which contains 10 rows and 3 columns.. Now i want to loop through all rows and all columns of the gridview and want to add them to a datatable..
DataRow row;
int rowscount = gv.Rows.Count;
int columnscount = gv.Columns.Count;
for (int i = 0; i < rowscount; i++)
{
for (int j = 0; j < columnscount; j++)
{
row = empTable.NewRow();
row["a"] = gv.Rows[i][column1].Tostring();
row["b"] = gv.Rows[i][column2].ToString();
MynewDatatable.Rows.Add(row);
}
}
gv - my gridview
Now my question is , Can i get the value of all columns of all rows in gv to my new datatable.. I dont know whether my loop is correct or not... I am using this datatable for a bulkcopy function...
Your code above is creating a new Row for every cell in the GridView.
within each row of the GridView your code is assigning every value in the row to the same column, Emp_Name.
Corrected, I think:
int rowscount = gv.Rows.Count;
int columnscount = gv.Columns.Count;
for (int i = 0; i < rowscount; i++)
{
// Create the row outside the inner loop, only want a new table row for each GridView row
DataRow row = empTable.NewRow();
for (int j = 1; j < columnscount; j++)
{
// Referencing the column in the new row by number, starting from 0.
row[j - 1] = gv.Rows[i][j].Tostring();
}
MynewDatatable.Rows.Add(row);
}
EDIT: You've been editing the source in your question, so my answer may grow out-of-date. :)
Your loop is incorrect, all lists start at 0. But you start at 1 when looping through the columns.
The JMD answer is correct, but depending on your use-case, maybe databinding the DataSource of your grid view to your DataTable would be a better approach.
Try this code:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
string selectedempid = dataGridView1.SelectedRows[0].Cells["Deptno"].Value.ToString();
{
SqlCommand cmd = new SqlCommand("delete from Test_dept where Deptno=" + selectedempid, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("deleted");
}
}

Categories

Resources