Send selected datagridview to datatable - c#

I'm trying to get a selected datagridview row to a datatable.
With the following code I am able to send the selectedrow over, however when trying to send a second row to the datatable, it adds an empty row but overwrites the first row in the datatable.
for (int i = 0; i < dataGridview.SelectedRows.Count; i++)
{
DT1.Rows.Add();
for (int j = 0; j < dataGridview.Columns.Count; j++)
{
DT1.Rows[0][j] = dataGridview.SelectedRows[i].Cells[j].Value;
}
}
As expected it enters the row on index 0, so i tried the folowing to get to the last row
for (int j = 0; j < dataGridview.Columns.Count; j++)
{
int rowcount = DT1.Rows.Count;
DT1.Rows[rowcount][j] = dataGridview.SelectedRows[i].Cells[j].Value;
}
This gives me an error that the row does not exist, what should be the solution to add a second row instead of replacing?

You've got other problems in your code. Namely, if your user selects the same rows in different calls to this code, you will insert duplicates.
Fix rowcount, changing it to rowcount-1. Then review your design. Come up with an approach to prevent duplicate insertions (unless you really want that).

You have a problem in rowcount
Rowcount gives you total no of rows but rowindex always starts with 0
ie rowindex = rowcount-1
use this
for (int j = 0; j < dataGridview.Columns.Count; j++)
{
int rowcount = DT1.Rows.Count;
DT1.Rows[rowcount-1][j] = dataGridview.SelectedRows[i].Cells[j].Value;
}

DT1.Rows[i][j] = dataGridview.SelectedRows[i].Cells[j].Value,ToString();
Try this! Your outer loop is already keeping track of the rows in your tables so there's no need to mess with the row count.

Related

Simplest way of programmatically creating a DataGridView with X columns by Y rows

In C# Winforms, I'd like to use a DataGridView as a simple widget to store information to display to the user. To this end, I'd like to create a table of say, 5x10 cells.
After some research, solutions tend to allow adding just one row or column at a time. I'd like the whole grid created initially and straight away, so I can start populating it with data, like you would with a standard C# 2D array.
What's the simplest way of going about this? A function header could look like this:
createCells(DataGridView dgv, int cols, int rows) {}
It should be quick and amenable to changing the cols and rows to a larger or smaller number later on if need be.
By the way, there might an error like:
Sum Of The Columns' FillWeight Values Cannot Exceed 65535
To avoid it, set AutoGenerateColumns property to false, and set FillWeight to 1 for each column generated:
dgv.AutoGenerateColumns = false;
for (int i = 1; i <= columns; i++)
{
dgv.Columns.Add("col" + i, "column " + i);
dgv.Columns[i - 1].FillWeight = 1;
}
for (int j = 0; j < rows; j++)
dgv.Rows.Add();
You can do by using for loops in this way:
private DataGridView DGV_Creation(DataGridView dgv, int columns, int rows)
{
for (int i = 1; i <= columns; i++)
{
dgv.Columns.Add("col" + i, "column " + i);
}
for (int j = 0; j < rows; j++)
{
dgv.Rows.Add();
}
return dgv;
}
Call it with:
this.dataGridView1 = DGV_Creation(dataGridView1, 5, 10); // 5 columns, 10 rows (empty rows)
or:
private void DGV_Creation(ref DataGridView dgv, int columns, int rows)
{
for (int i = 1; i <= columns; i++)
dgv.Columns.Add("col" + i, "column " + i);
for (int j = 0; j < rows; j++)
dgv.Rows.Add();
}
call it with:
DGV_Creation(ref this.dataGridView1, 5, 10); //5 columns, 10 rows (empty rows)

c# winforms DataGridViewRow.Index and Count

What is wrong with this code
for (int i = 1; i < dgv.Rows.Count;)
{
MessageBox.Show(dgv.Rows[i].Index.ToString());
}
I'm getting endless MsgBoxes displaying allways and only value "1"
dgv has six rows.
you forget to place i++
and also i = 0; if i = 1 you will be miss first row of gridview
for (int i = 0; i < dgv.Rows.Count;i++)
{
MessageBox.Show(dgv.Rows[i].Index.ToString());
}

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";
}
}
}

Datatable and Datagridview

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).

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