Move row to top in data table c# - c#

I have a data table in which if the Addresses match move one of the rows to the top of the data table. I am using the following code but it doesnt work. Any idea how to achieve this. The data in the data table is imported from an excel file. I have tried the same if statement in GridView to highlight the duplicates and that works but I also want to move them to the top because the data has more than 1000 rows and its hard to move up and down again and again to check for the highlighted row.
for (int row = 1; row < dtf1.Rows.Count; row++)
{
for (int rowinner = 1; rowinner < dtf1.Rows.Count; rowinner++)
{
if (rowinner != row)
{
if (dtf1.Rows[row][addresscolno] == dtf1.Rows[rowinner][addresscolno].ToString())
{
DataRow newrow = dtf1.Rows[row];
dtf1.Rows.RemoveAt(row);
dtf1.AcceptChanges();
dtf1.Rows.InsertAt(newrow, 1);
dtf1.AcceptChanges();
GridView1.DataSource = dtf1;
GridView1.DataBind();
}
}
}
}

So you want to reorder the DataTable. The row with a given address should be on the top. You can use Linq-To-DataSet to order the rows and CopyToDataTable to create a new DataTable with the new order:
// assuming the address is a string in a variable address, to simplify matters
DataTable tblOrdered = dtf1.AsEnumerable()
.OrderByDescending(r => r.Field<string>("addresscolno") == address)
.ThenBy(r => r.Field<string>("addresscolno"))
.CopyToDataTable();
Then you can use that as DataSource for your GridView.
Edit: Give also DataTable.Rows.InsertAt a try.
dtf1.Rows.InsertAt(dtf1.Rows[rowinner], 0);

Related

How to copy values from a datatable column into a datagridview column in windows forms in c# without iterating every single row?

I have more than 9000 rows and 18 columns in my datagridview. I have to read the columns from an external datatable. If I find a match between column names, I have to copy all values from the datatable column into the datagridview column. My problem is, I cannot iterate over these rows for 18 times for more than 9000 rows and write for every iteration the value in the datagridview cell because it is too slow. Is there any valid alternative?
I add some code below so that you can understand better my question. Here I'm iterating the columns first, then the rows. Sorry for the indentation but I'm having problems in copy paste code on StackOverflow.
dgvMappatura is my dataGridView, dtExcel is my DataTable
foreach (DataColumn col in dtExcel.Columns)
{
if (col.ColumnName.Equals(nome_colonna_origine))
{
foreach (DataRow drExcel in dtExcel.Rows)
{
// some code to add values to datagridview from the datatable column
}
}
}
See if following is faster :
DataTable dt = new DataTable();
foreach (DataRow row in dt.AsEnumerable())
{
var matches = row.ItemArray.Select((x, i) => new { name = x.ToString(), index = i }).GroupBy(x => x.name).Where(x => x.Count() > 1).ToArray();
}

Removing certain row from datatable C#

I am trying to remove rows from datatable in which a certain cell is empty. I have tried using for loop but to no avail.
for (int i = dtbl.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dtbl.Rows[i];
if (dr["id"] == null)
dtbl.Rows.Remove(dr);
}
If the cell of ID column is empty, then that row should be deleted.
Any help is appreciated. Thanks in advance.
Change your test to this one.
for (int i = dtbl.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dtbl.Rows[i];
if (dr.IsNull("id"))
dtbl.Rows.Remove(dr);
}
See docs: DataRow.IsNull
or you can use a check against the special field DbValue.Null
if (dr["id"] == DbNull.Value)
Another approach is this one
for (int i = dtbl.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dtbl.Rows[i];
if (dr.IsNull("id"))
dr.Delete();
}
dtbl.AcceptChanges();
this last one just marks the row for deletion, but the row remains in the table until you call AcceptChanges. (So this approach is suitable for a foreach loop)
Calling DataRow.Delete is the preferred way to work if you plan to update the real database table at later time (for example when you want your user delete many rows from a bound grid and then make a single update to the database only if the user clicks on a Save button).
You could use linq to select those not null
dtbl = dtbl.AsEnumerable()
.Where(r => r.Field<string>("id") != null)
.CopyToDataTable();
Might need the type, specify that nullable type to compare row.Field<int?>("id").HasValue

How can I send the selected rows of a DataGridView to a Datatable, BUT ignoring the first column?

Hellou to everyone.
I would love the assistance from you guys.
My problem is like this:
I have this datagridview which I fill using datasource (a query to a db table). I only created manually one column which contain a checkbox. When the binding is complete I can click the checkboxes to select the row and I can select multiples rows this way.
I want to put the selected rows into a datatable (so I can read it and do some sql queries with the information on it) BUT when I read the selected rows to put them inside a datatable I need to skip the checkbox column (the first one).
How can I achieve this?
Okay, for future reference, I'm gonna post here how I fixed it.
DataTable dt = new DataTable();
if (dgvPedidos.SelectedRows.Count > 0)
{
foreach (DataGridViewColumn column in dgvPedidos.Columns)
dt.Columns.Add();
int i = 0;
foreach(DataGridViewRow row in dgvPedidos.Rows)
{
if (Convert.ToBoolean(dgvPedidos.Rows[i].Cells["chkPedido"].Value) == true)
{
dt.Rows.Add();
dt.Rows[i][1] = row.Cells[1].Value.ToString();
dt.Rows[i][2] = row.Cells[2].Value.ToString();
dt.Rows[i][3] = row.Cells[3].Value.ToString();
dt.Rows[i][4] = row.Cells[4].Value.ToString();
dt.Rows[i][5] = row.Cells[5].Value.ToString();
dt.Rows[i][6] = row.Cells[6].Value.ToString();
dt.Rows[i][7] = row.Cells[7].Value.ToString();
dt.Rows[i][8] = row.Cells[8].Value.ToString();
dt.Rows[i][9] = row.Cells[9].Value.ToString();
i++;
}
}
dt.Columns.RemoveAt(0);

database connection to datagridview's row only

I Have requirement to fill the datagridview row by row . i.e. if 3rd row is currently selected then data needs to be filled in 3rd row (my query returns always single row ) . same for every row.
some what like
DataTable dt = new DataTable();
dataadapter.Fill(dt);
dataGridView1.Rows[index].DataSource = dt; (just a hunch, but not working)
(instead of ) //dataGridView1.DataSource = dt;
hope that I made my requirement clear to you
Is their any way to accomplish it ....
Thanks in advance....
If your query returns a single row then you just have to fill the columns with correct values from your query:
dataGridView1.Rows[rowIndex].Cells["ColumnName"].Value =
dt.Rows[0]["ColumnNameInDataTable"].ToString();
Your grid will not be bound to the data this way. But it will fill the columns in the current row like you've asked.
I don't think this is possible directly,
You could use a List with a certain amount of empty objects and bind this List to your DataGridView... Then you would have empty Rows to work with. You can then fill single rows of the List with data and update the binding.
I also think you need a BindingSource and not a DataTable in this case...
Something like this:
private List<YourObject> gridData; // List
private BindingSource bindingSource;
public void Init()
{
this.gridData = new List<Anything>();
//prefill list, in this case we want to have 100 empty rows in DataGrid
for (var i = 0; i < 100; i++)
{
this.gridData.Add(new YourObject());
}
this.bindingSource.DataSource = this.gridData;
}
public void UpdateRow(int row)
{
this.gridData[row] = (from .. in select ...).FirstOrDefault(); // your query
}

Add Datagridview Rows to Datatable when Checkbox is Checked in C#

i am working with Desktop Application and i am trying to create a datatable from a datagridview. but i only want to add those rows when checkbox is selected or checked. currently i created a datatable from a whole datagridview like this.
DataTable tbl = (DataTable)dataGridView1.DataSource;
I have added a checkbox coloumn inside datagridview.. so please guide me how to add selected rows to a new datatable
Thanks.. Here is the new code Update
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value) == true)
{
DataRow dr0 = tbl.NewRow();
dr0["ID"] = dataGridView1.Rows[i].Cells["ID"].Value;
dr0["BikeCC"] = dataGridView1.Rows[i].Cells["BikeCC"].Value.ToString();
dr0["ChassisModel"] = dataGridView1.Rows[i].Cells["ChassisModel"].Value.ToString();
dr0["BikeCC"] = dataGridView1.Rows[i].Cells["BikeCC"].Value.ToString();
dr0["ChassisModel"] = dataGridView1.Rows[i].Cells["Chassismodel"].Value.ToString();
tbl.Rows.Add(dr0);
}
}
objMdl.RecordTable = tbl;
This is the way i could find to add selected rows into a new datatable... it is lenghty but i am still facing little issues. which i will post in a bit for your look.
Suppose your checkbox column is named yourCheckBoxColumn:
DataTable tbl = ((DataTable)dataGridView1.DataSource).Clone();//Clone structure first
var rows = dataGridView1.Rows.OfType<DataGridViewRow>()
.Where(r=>Convert.ToBoolean(r.Cells["yourCheckBoxColumn"].Value))
.Select(r=>((DataRowView)r.DataBoundItem).Row);
foreach(var row in rows)
tbl.ImportRow(row);

Categories