row.clone is not working when the datatable bind to datasourse - c#

datagridview dgv is bind to datatable dt.
dgv_copy is new datagridview.dgv_copy is add row to dgv by using row.clone.
my code is
if (dgv_copy.Columns.Count == 0)
{
foreach (DataGridViewColumn dgvc in dgv_org.Columns)
{
dgv_copy.Columns.Add(dgvc.Clone() as DataGridViewColumn);
}
}
DataGridViewRow row = new DataGridViewRow();
for (int i = 0; i < dgv_org.Rows.Count; i++)
{
row = (DataGridViewRow)dgv_org.Rows[i].Clone();
int intColIndex = 0;
foreach (DataGridViewCell cell in dgv_org.Rows[i].Cells)
{
row.Cells[intColIndex].Value = cell.Value;
intColIndex++;
}
dgv_copy.Rows.Add(row);
}
dgv_copy.AllowUserToAddRows = false;
dgv_copy.Refresh();
source is https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.clone.aspx

Because original DataGridView is bounded to the DataTable you can create copy of DataTable and boud it to the second DataGridView.
var original = (DataTable)originalDataGridView.DataSource;
var copy = original.Copy();
copyDataGridView.DataSource = copy;

Pretty sure you could just do dgv_copy.rows.add(dgv_org.Rows[i].ItemArray)

Related

Read Checkboxvalues that were dynamically created in a Datatable c#

I have this code that dynamically created my checkboxes. I have several columns of checkboxes and several rows, so it needs to be totally dynamical.
I don't know how i can read the values of the checkboxes and would like to ask for some help. BTW I would like to save the values in a multidimensional array.
Meldungtable.Columns.Add("Warnungen", typeof(string));
for (int meldungcnt = 0; meldungcnt < SPSWarnungsBausteinArray.Length; meldungcnt++)
{
Meldungtable.Rows.Add(SPSWarnungsBausteinArray[meldungcnt]);
}
WarnungenDataGridView.DataSource = Meldungtable;
for (int kameracnt = 1; kameracnt <= Kameraanzahl; kameracnt++)
{
DataGridViewCheckBoxColumn Kamerachk = new DataGridViewCheckBoxColumn();
Kamerachk.HeaderText = "Kamera" + kameracnt;
Kamerachk.Name = "KameraChkBox" + kameracnt;
Kamerachk.Width = 70;
WarnungenDataGridView.Columns.Add(Kamerachk);
}
I would read row by row and check for the checkbox name, that i have assigned before, but as I am reading the data in a different method I don't think this works out.
Please help
Display:
foreach (DataGridViewRow row in WarnungenDataGridView.Rows)
{
for (int col = 1; col < WarnungenDataGridView.ColumnCount; col++)
{
//DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[col];
WarnungenDataGridView.Rows[row.Index].Cells[col].Value = "true";
}
}
foreach (DataGridViewRow row in WarnungenDataGridView.Rows)
{
DataGridViewCheckBoxCell CheckedCell = row.Cells[0] as DataGridViewCheckBoxCell;
if (CheckedCell.Value != null)
{
if (CheckedCell.Value == CheckedCell.TrueValue)
{
//It's checked! do something within your code where necessary
}
}
}

Add specific rows from dataGridView depending on search value

Following issue:
I have a datatable and a list which contains specific values.
routIds = col1Items.Distinct().ToList();
String searchValue = String.Empty;
int rowIndex = -1;
for (int i = 0; i < routIds.Count; i++)
{
searchValue = routIds[i];
foreach (DataGridViewRow row in form1.dataGridView5.Rows)
{
if (row.Cells[form1.routingIdBox.Text].Value != null) // Need to check for null if new row is exposed
{
if (row.Cells[form1.routingIdBox.Text].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
foreach (DataGridViewColumn column in form1.dataGridView5.Columns)
dtRout.Columns.Add(column.Name);
for (int k = 0; k < form1.dataGridView5.Rows.Count; k++)
{
dtRout.Rows.Add();
for (int j = 0; j < form1.dataGridView5.Columns.Count; j++)
{
datTable.Rows[k][j] = form1.dataGridView5.Rows[rowIndex].Cells[j].Value;
}
}
}
}
}
}
I want to search the first column from my datagridview and check if it matches a specific value (from my array - routIds). If yes then I want to add the whole row into a datatable but I don't know how this works exactly. Tried around but I get exceptions (specific row not found).
Assuming you have a DataTable as your underlying DataSource. I would not iterate through the DataGridViewRows.
DataTable dataSource = dataGridView.DataSource as DataTable; // if it is a DataTable. If not, please specify in your question
// let's make a DataTable, which is a copy of your DataSource
DataTable dataTableFoundIds = new DataTable();
foreach (DataColumn column in dataSource.Columns)
dataTableFoundIds.Columns.Add(column.ColumnName, column.DataType);
// iterate through your routeIds
foreach (int id in routeIds)
{
var row = dataSource.AsEnumerable().FirstOrDefault(item => item["col1"].Equals(id)); // take the first row in your DataSource that matches your routeId
if (row != null)
{
dataTableFoundIds.Rows.Add(row.ItemArray); // if we find something, insert the whole row of our source table
}
}
Hope this helps!
UPDATE: if you want to find all occurances:
foreach (int id in routeIds)
{
var rows = dataSource.AsEnumerable().Where(item => item["col1"].Equals(id)); // take all rows in your DataSource that match your routeId
foreach(var row in rows)
{
dataTableFoundIds.Rows.Add(row.ItemArray); // if we find something, insert the whole row of our source table
}
}

Putting a listbox/dropdown menu in a data grid view C#

I have a data table in a data grid view. I want to put an listbox/dropdown menu in a specific column and row. I have tried this but it doesn't work --
var column = new DataGridViewComboBoxColumn();
RunTimeCreatedDataGridView[1, 1].Value = RunTimeCreatedDataGridView.Columns.Add(column);
Here is how I populate the table--
public DataTable createGridForForm(int rows, int columns)
{
// Create the output table.
DataTable table = new DataTable();
for (int i = 1; i <= columns; i++)
{
table.Columns.Add("column " + i.ToString());
}
for (int i = 1; i < rows; i++)
{
DataRow dr = table.NewRow();
// populate data row with values here
ListBox test = new ListBox();
myTabPage.Controls.Add(test);
table.Rows.Add(dr);
}
return table;
}
And here is how I create the datagridview.
private void createGridInForm(int rows, int columns)
{
DataGridView RunTimeCreatedDataGridView = new DataGridView();
RunTimeCreatedDataGridView.DataSource = createGridForForm(rows, columns);
//DataGridViewColumn ID_Column = RunTimeCreatedDataGridView.Columns[0];
//ID_Column.Width = 200;
int positionForTable = getLocationForTable();
RunTimeCreatedDataGridView.BackgroundColor = Color.WhiteSmoke;
RunTimeCreatedDataGridView.Size = new Size(995, 200);
RunTimeCreatedDataGridView.Location = new Point(5, positionForTable);
myTabPage.Controls.Add(RunTimeCreatedDataGridView);
}
You were right on track with your first code block... the problem was you were trying to add a column to a cell reference. If you want to add a column where all rows have a drop down, then do exactly what you were doing, but simply add the column instead of specifying a cell value, like this:
var column = new DataGridViewComboBoxColumn();
RunTimeCreatedDataGridView.Columns.Add(column);
Then, specify the datasource as you normally would for a combobox.
Alternatively, if you want a specific cell to have a different combobox, or only a single cell in the column to have one, you can create a separate one as shown here or here.
Edit: To add a combobox to a specific cell in the DataGridView, you would do something like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridView dgv = new DataGridView();
// add some columns and rows
for (int i = 0; i < 10; i++)
{
DataGridViewCell c = new DataGridViewHeaderCell();
dgv.Columns.Add("Column" + i, Convert.ToString(i));
}
for (int i = 0; i < 10; i++)
{
dgv.Rows.Add(new DataGridViewRow());
}
//create a new DataGridViewComboBoxCell and give it a datasource
var DGVComboBox = new DataGridViewComboBoxCell();
DGVComboBox.DataSource = new List<string> {"one", "two", "three"};
DGVComboBox.Value = "one"; // set default value of the combobox
// add it to cell[4,4] of the DataGridView
dgv[4, 4] = DGVComboBox;
// add the DataGridView to the form
this.Controls.Add(dgv);
}
}

Issue with adding new empty row in a gridview control using a button

I've a gridview which is forever in an edit mode(Pageload). I've added a button at the footer of the gridview in order to add a new row to insert values. Now, the problem is that when I want to edit the data from database. The data will bind into the gridview and if I click on the button to add new row, the data which was already exist in the gridview will disappear except the 1st row.
This the code under add new row button:
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
DataRow tempRow = null;
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's values
var txtProblem =
(TextBox)gvTroubleshooting.Rows[rowIndex].Cells[2].FindControl("txtProblem");
var txtCorrectiveMessure =
(TextBox)gvTroubleshooting.Rows[rowIndex].Cells[3].FindControl("txtCorrectiveMessure");
// Create new row and update Row Number
tempRow = tempTable.NewRow();
tempTable.Rows[i - 1]["Problem"] = txtProblem.Text;
tempTable.Rows[i - 1]["Corrective_Measures"] = txtCorrectiveMessure.Text;
rowIndex++;
}
// Add data to datatable and viewstate
tempTable.Rows.Add(tempRow);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
gvTroubleshooting.DataSource = tempTable;
gvTroubleshooting.DataBind();
}
}
//Set Previous Data on Postbacks
SetPreviousData();
}
SetPreviousData() code is as follows:
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 0; i < tempTable.Rows.Count; i++)
{
var txtProblem =
(TextBox)gvTroubleshooting.Rows[rowIndex].Cells[2].FindControl("txtProblem");
var txtCorrectiveMessure =
(TextBox)gvTroubleshooting.Rows[rowIndex].Cells[3].FindControl("txtCorrectiveMessure");
txtProblem.Text = tempTable.Rows[i]["Problem"].ToString();
txtCorrectiveMessure.Text = tempTable.Rows[i]["Corrective_Measures"].ToString();
rowIndex++;
}
}
}
}
Any help is greatly appreciated!!
Try adding your existing datagridview data to a temporary datatable and merge it with the newly added datatable.Now set the merged datatable as your datasource to the datagridview

Copy Data Table to a Data Grid without binding them together

I have two datagrids in my application (dataGridView1 and dataGridView2). I am moving selected items from dataGridView1 into dataGridView2. Here is how I am currently doing this:
DataTable dt = new DataTable("dt");
DataTable id = new DataTable("id");
try
{
if (dataGridView1.Rows.Count > 0)
{
for (int i = 0; i < dataGridView1.Rows.Count - 0; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value != null)
{
DataRow row;
DataRow idRow;
row = dt.NewRow();
idRow = id.NewRow();
idRow["id"] = dataGridView1.Rows[i].Cells[1].Value.ToString();
row["id"] = dataGridView1.Rows[i].Cells[1].Value.ToString();
row["Link Name"] = dataGridView1.Rows[i].Cells[2].Value.ToString();
dt.Rows.Add(row);
id.Rows.Add(idRow);
}
}
dataGridView2.DataSource = dt;
}
However, I also need to be able to remove items from dataGridView2. Currently, the DataTable dt is bound to dataGridView2 and I cant clear it after the items are added because it also clears the dataGridView2.
Basicly, my question would be, is there a way to add the contents of a data table to a data grid without using datagrid.DataSource?
You can manually add each row using the dataGridView2.Rows.Add function. Also, I have typically used the dataGridView2.Row(n).Tag to hold the actual source of that row's data.
int n = dataGridView2.Rows.Add();
DataGridViewRow newRow = dataGridView2.Rows[n];
newRow.Cells[0].Value = "ABC";
newRow.Cells[1].Value = 123;
newRow.Tag = row;

Categories