add selected row from one gridview to another - c#

I have 2 GridView controls. I need to add the selected row from one GridView to a second GridView. (I select row from GridView by clicking direct to GridView.)
Here's my code, but it copies all data from gridview1 to gridview2. I need the selected row only.
private void button6_Click(object sender, EventArgs e)
{
DataGridViewColumn newCol = null;
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
newCol = new DataGridViewColumn(col.CellTemplate);
newCol.HeaderText = col.HeaderText;
newCol.Name = col.Name;
dataGridView2.Columns.Add(newCol);
}
dataGridView2.RowCount = dataGridView1.RowCount;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dataGridView2.Rows[row.Index].Cells[col.Name].Value = row.Cells[col.Name].Value;
}
}
I populated dataGridView1 with a DataTable:
SqlConnection con = new SqlConnection(#"Data Source=AFZAL\SQLEXPRESS;Initial Catalog=GIMS_LabInfo;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("SELECT PROFCODE,PROFNAME FROM PROFNAMES$ WHERE (PROFNAME LIKE '" + textBox1.Text + "%') AND PROFCODE NOT IN (SELECT PROFCODE FROM MAP) ORDER BY Profname desc ", con);
sc.ExecuteNonQuery();
SqlDataAdapter sda = new SqlDataAdapter(sc);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;

Immediately after setting dataGridView1.DataSource:
dataGridView1.DataSource = yourDataTable;
Set dataGridView2.DataSource to clone the structure (such as Columns) of the first DataTable:
dataGridView2.DataSource = yourDataTable.Clone();
Or:
dataGridView2.DataSource = ((DataTable)dataGridView1.DataSource).Clone();
Then in your button click event, all you need is this:
private void button6_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow == null)
return;
var currentRow = ((DataRowView)dataGridView1.CurrentRow.DataBoundItem).Row;
((DataTable)dataGridView2.DataSource).ImportRow(currentRow);
}
How can I add multiple rows on each click? As right now when I select second row, it replaces the First one in dataGridView2.
If you have multiple selected rows, you'll have to iterate over the SelectedRows property. Try this:
private void button1_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow == null)
return;
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
((DataTable)dataGridView2.DataSource).ImportRow(((DataRowView)row.DataBoundItem).Row);
}

Related

how to filter a column in datagridview imported from excel file

For example I have a datagridview1 with data imported from a excel file and there are 12 columns: date, Name, Activity, Project,time, comment,ect. and 1000 row.
What I want to do is to filter only all with the Project name in project column.
for example I have support as a (Projectname) I want to show all columns filtyring by support rows.
I have combobox to select which column I need to filter it( e.g Project) here,
I tried with this code but it dose not work.
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string projektItem = comboBox1.Items[comboBox1.SelectedIndex].ToString();
if (projektItem == "Project") {
foreach (DataRow dataRow in dataGridView1.Rows)
{
StringBuilder filter = new StringBuilder();
for (int i = 0; i < dataGridView1.Columns.Count - 1; i++)
{
filter.Append(dataRow[i].ToString());
filter.Append("\t");
}
dataGridView1.DataSource = filter.ToString();
}
if (projektItem == "Name") {
}
if (projektItem == "Aktivity") {
}
}
This is how I do it. convert datagridview to datatable
And this is func for filter purpose:
Hold the origin table to go back if you turn your filter off
//datagrid to datatable
DataTable datatable = new DataTable();
datatable = (DataTable)dataGridView1.DataSource;
//datatableOrigin to hold your origin table
DataTable originTable = null;
// find Function
Public void Find(string column, string st)
{
DataRow[] dtResult;
DataTable holder = New DataTable;
//get datatable Schema
DataTable holder = datatable.Clone();
holder.Rows.Clear();
If (originTable != null)
datatable = originTable;
Else
originTable = datatable;
//select return datarow array
dtResult = datatable.Select("[" + column + "] LIKE '%" + st + "%'");
//import all your result into holder
foreach(DataRow dr In dtResult){holder.ImportRow(dr);}
//pass from holder to datatable
datatable = holder.Copy();
holder.Clear();
}
public void showDT()
{
dataGridView1.DataSource = datatable;
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// choose your column here
}
private void btn_Clicked(object sender, EventArgs e)
{
Find('YourColumn, 'your search string);
showDT();
}

bind asp.net gridview column form textbox value dynamically

I want to bind gridview column from textbox value for example: I have two textbox and a button what i exactly want that i will give input in the two textboxes and when i clicked the button the textbox values will show in gridviw and want to do this for multiple times without replacing the previous values.
I found so many relevant answer but all are done with hard code inside button click event
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name",
typeof(string)),
new DataColumn("Age", typeof(decimal)) });
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind()
}
which replace the previous values when i insert new values, but i want to keep all the previous values in which I stuck .thanks
this code will help you to get current data from gridview to datatable
and then you can append new rows accordingly .
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt =GetGridData();
dr = dt.NewRow();
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind();
}
private DataTable GetGridData ()
{
DataTable _datatable = new DataTable();
for (int i = 0; i < grdReport.Columns.Count; i++)
{
_datatable.Columns.Add(grdReport.Columns[i].ToString());
}
foreach (GridViewRow row in grdReport.Rows)
{
DataRow dr = _datatable.NewRow();
for (int j = 0; j < grdReport.Columns.Count; j++)
{
if (!row.Cells[j].Text.Equals(" "))
dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
}
_datatable.Rows.Add(dr);
}
return _dataTable;
}
You can store the values from each PostBack into a Session or ViewState, otherwise you'll lose all the data when the button is clicked again.
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt;
//check if the datatable already exists in the viewstate, if not create a new datatable
if (ViewState["myTable"] == null)
{
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name", typeof(string)), new DataColumn("Age", typeof(decimal)) });
}
else
{
//correct viewstate exists, cast back to a datatable
dt = ViewState["myTable"] as DataTable;
}
//add the new values
dt.Rows.Add(TextBox1.Text, Convert.ToDecimal(TextBox2.Text));
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//save the datatable into the viewstate
ViewState["myTable"] = dt;
//clear the textboxes
TextBox1.Text = "";
TextBox2.Text = "";
}

How to add database columns from table to combobox

private void Form1_Load(object sender, EventArgs e)
{
con.Open();
DataTable dt = con.GetSchema("TABLES").AsEnumerable().Where(x => x.Field<string>("TABLE_TYPE") == "TABLE").CopyToDataTable();
foreach (DataRow r in dt.Rows)
comboBoxTabel.Items.Add(r["TABLE_NAME"].ToString());
con.Close();
}
private void comboBoxTabel_SelectedIndexChanged(object sender, EventArgs e)
{
//con.Open();
//DataTable dt = con.GetSchema("COLUMNS");
//foreach (DataRow r in dt.Rows)
//comboBoxKolom.Items.Add(r.Field<string>("COLUMN_NAME"));
}
Can someone help me out please? When the program loads it shows all the tables from the database in the first combobox (comboBoxTabel). What i want is when you click on a table, that the columns of that table appear in the 2nd combobox (comboBoxKolom).

Move selected row from DataGridView to another in Visual C#

I created a form with two Datagridviews. One of these DataGridViews is filled with data from a Database and it is the source. The second DataGridView should be filled with the selected rows from the source Datagridview after I use a Button.
The first step if fill my DataTable is filled this :
public DataTable loadMatImpTable(String query)
{
myConn.Open();
SQLiteCommand cmd = new SQLiteCommand(query, myConn);
SQLiteDataAdapter sda = new SQLiteDataAdapter();
sda.SelectCommand = cmd;
DataTable dt= new DataTable();
sda.Fill(dt);
return dt;
}
After that I fill my source DataGridView:
DataTable dt = lt.loadMatImpTable(queryMat);
this.matExpDataGridVW.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = matExpDataGridVW.Rows.Add();
matExpDataGridVW.Rows[n].Cells[0].Value = false;
matExpDataGridVW.Rows[n].Cells[1].Value = item["MaterialID"].ToString();
matExpDataGridVW.Rows[n].Cells[2].Value = item["Name"].ToString();
matExpDataGridVW.Rows[n].Cells[3].Value = item["Preis"];
matExpDataGridVW.Rows[n].Cells[4].Value = item["Anzahl"].ToString();
matExpDataGridVW.Rows[n].Cells[5].Value = item["Datum"].ToString();
}
And then I push the "ExportButton" and all Selected Rows are copied to the second DatagRidview. But I don't wont't a copy of the rows in the second DataGridview. I will move the selected rows. So I tried in a remove of the items in a foreach loop:
private void mvImpSelectionBT_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in matExpDataGridVW.Rows)
{
if ((bool)item.Cells[0].Value == true)
{
int n = matImpDataGridVW.Rows.Add();
matImpDataGridVW.Rows[n].Cells[0].Value = false;
matImpDataGridVW.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
matImpDataGridVW.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
matImpDataGridVW.Rows[n].Cells[3].Value = item.Cells[3].Value.ToString();
matImpDataGridVW.Rows[n].Cells[4].Value = item.Cells[4].Value.ToString();
matImpDataGridVW.Rows[n].Cells[5].Value = item.Cells[5].Value.ToString();
}
}
#Delete all Selected rows
foreach (DataGridViewRow item in matExpDataGridVW.SelectedRows)
{
matExpDataGridVW.Rows.Remove(item);
}
}
But if I tried the deletion in this way. All selected rows be copied but only the last selected row be deleted in the source DatGridView. Whats the best way to delete this selected rows?
Create a list of rows while you are copying, and then use that list as a basis for deleting your rows from the source.
private void mvImpSelectionBT_Click(object sender, EventArgs e)
{
List<DataRow> rowsToDelete = new List<DataRow>();
foreach (DataGridViewRow item in matExpDataGridVW.Rows)
{
if ((bool)item.Cells[0].Value == true)
{
//copy row
int n = matImpDataGridVW.Rows.Add();
matImpDataGridVW.Rows[n].Cells[0].Value = false;
matImpDataGridVW.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
matImpDataGridVW.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
matImpDataGridVW.Rows[n].Cells[3].Value = item.Cells[3].Value.ToString();
matImpDataGridVW.Rows[n].Cells[4].Value = item.Cells[4].Value.ToString();
matImpDataGridVW.Rows[n].Cells[5].Value = item.Cells[5].Value.ToString();
//add to list
rowsToDelete.Add(item);
}
}
foreach(DataRow row in rowsToDelete)
{
matExpDataGridVW.Rows.Remove(row);
}
}
Another way to do this, with only one loop, is to use a loop with an iterator instead of a foreach loop.
for (int i = matExpDataGridVW.Rows.Count - 1; i >= 0; i--)
{
if ((bool)matExpDataGridVW.Rows[i].Cells[0].Value == true)
{
//copy row
int n = matImpDataGridVW.Rows.Add();
matImpDataGridVW.Rows[n].Cells[0].Value = false;
matImpDataGridVW.Rows[n].Cells[1].Value = matExpDataGridVW.Rows[i].Cells[1].Value.ToString();
matImpDataGridVW.Rows[n].Cells[2].Value = matExpDataGridVW.Rows[i].Cells[2].Value.ToString();
matImpDataGridVW.Rows[n].Cells[3].Value = matExpDataGridVW.Rows[i].Cells[3].Value.ToString();
matImpDataGridVW.Rows[n].Cells[4].Value = matExpDataGridVW.Rows[i].Cells[4].Value.ToString();
matImpDataGridVW.Rows[n].Cells[5].Value = matExpDataGridVW.Rows[i].Cells[5].Value.ToString();
//delete row
matExpDataGridVW.Rows[i].Delete();
}
matExpDataGridVW.AcceptChanges();
}
If you want "move"(add to destination and remove from source) selected rows to another DataGridView. Try to move items by using DataSources
Load data to original DataGridView
private DataTable _OriginalData;
private DataTable _SelectedData;
private void LoadData()
{
string yourQuery = "SELECT ... FROM ...";
_OriginalData = loadMatImpTable(yourQuery);
//copy structure of original DataTable to the selected table
_SelectedData = _OriginalData.Clone();
//Fill DataGridView
this.matExpDataGridVW.DataSource = _OriginalData;
this.matImpDataGridVW.DataSource = _SelectedData;
//Columns will be generate automatically
//If you want use predefined columns create them through designer or with code
//And set then DataGridView.AutoGenerateColumns = false;
}
Then export items will be like this
private void ExportSelectedRows()
{
foreach DataRow row in matExpDataGridVW.SelectedRows
.Cast<DataGridViewRow>()
.Select(r => r.DataBoundItem as DataRowView)
.Where(drv => drv != null)
.Select(drv => drv.Row)
{
_SelectedData.ImportRow(row);
_OriginalData.Rows.Remove(row);
}
}

DataGridViewComboBoxCell valueValue is invalid with binded DataGridViewComboBoxCell

I have a DatagridView with two DataGridViewComboBoxCell:
Administration
Employee.
What I want to do is when I select an administration from 1st
DataGridViewComboBoxCell, I'll get the list of the employees of selected
Admininstration in the 2nd DataGridViewComboBoxCell. I binded the first
DataGridViewComboBoxCell manually to administrationBindingSource and I tried
this answer code, This is the code I used:
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
// This fires the cell value changed handler below
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
{
return;
}
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells["administrationColumn"];
int item = 0;
if (cb.Value != null)
{
item = (Int32)cb.Value;
selectEmployee(item);
dataGridView1.Invalidate();
}
}
private void selectEmployee(int idAdministration)
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
SqlCommand Cmd = new SqlCommand("SELECT * FROM Employee WHERE IdAdministration = #idAdministration", con);
Cmd.Parameters.AddWithValue("#idAdministration", idAdministration);
DataTable Dt = new DataTable();
Dt.Load(Cmd.ExecuteReader());
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells["Employee"];
cb.DataSource = Dt;
cb.DisplayMember = "Name";
cb.ValueMember = "CodeEmployee";
con.Close();
}
This code works fine in the first time but when I try to update admininstration value I got this error message:
DataGridViewComboBoxCell value is invalid
How to fix it?
Try to clear the value of employee cell before rebind it in the void
"selectEmployee", something like:
private void selectEmployee(int idAdministration)
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
SqlCommand Cmd = new SqlCommand("SELECT * FROM Employee WHERE IdAdministration = #idAdministration", con);
Cmd.Parameters.AddWithValue("#idAdministration", idAdministration);
DataTable Dt = new DataTable();
Dt.Load(Cmd.ExecuteReader());
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells["Employee"];
cb.Value = null; //add this
cb.DataSource = Dt;
cb.DisplayMember = "Name";
cb.ValueMember = "CodeEmployee";
con.Close();
}

Categories

Resources