Put selected rows from a GridView to a Listbox - c#

I'm trying the folowing:
List<object>selectedRows = new List<object>();
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
selectedRows.Add(row);
}
for (int i = 0; i < selectedRows.Count; i++)
{
selectedRowsList.Items.Add(selectedRows[i]);
}
I have a button and GridView. Now I want the user to select rows manually and store them in a List, so that I can put them into a Listbox (the values with "" or ";" side by side). So take the row from GridView and display it as a row in my Listbox. Multiple rows should be one below the other like it's displayed in the GridView). How to do that? The code i've posted stores the values as "{index = ...}".

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
listBox1.Items.Add(row.Cells[0].Value.ToString() +" "+row.Cells[1].Value.ToString() +" "+ row.Cells[2].Value.ToString());
}
When we select rows using RowHeader, we get result as below

This happens because Microsoft's ListBox displays the value of the DataGridViewRow object's ToString() method. Therefore you can fill the ListBox with string objects that are representation of every row in the DataGridView. So in the button's click event I modified your code as follows:
private void button1_Click(object sender, EventArgs e)
{
List<string> selectedRows = new List<string>();
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
string currentRow = string.Empty;
foreach (DataGridViewCell cell in row.Cells)
{
currentRow += String.Format("{0} ", cell.FormattedValue);
}
selectedRows.Add(currentRow);
}
for (int i = 0; i < selectedRows.Count; i++)
{
this.listBox1.Items.Add(selectedRows[i]);
}
}

Related

Getting the selected rows' values in datagridview and adding them up

I am making a booking winsform application now. When a user chooses any number of rows, there will be a column called rental price that each row is under. Then the value of this cell under the column called rental price will be gotten and add up and display to the total cost label text.But the problem is the total cost is not displaying. Here is my code:
private void Payment_Load(object sender, EventArgs e)
{
NameOfUser.Text = UserAccounts[0].Name;
EmailOfUser.Text = UserAccounts[0].Email;
PaymentType.Text = UserAccounts[0].PaymentType;
double totalCost = 0;
foreach (DataGridViewRow row in b1.DataGridView1.SelectedRows)
{
int index = 0;
foreach (DataGridViewCell cell in row.Cells)
{
totalCost += (double)dataGridView1.Rows[index].Cells[4].Value;
}
index++;
}
TotalCost.Text = Convert.ToString(totalCost);
}
Yes the Mistake is in the looping, As of now you are iterating the rows in the SelectedRows and by using the inner loop you again looping through the cells of each row But taking values with respect to the actual grid instead for the cell. You can make this simple as you wanted to iterate through the selected rows and need to sums the value of .Cells[4] in each row. for that you have to do something like this:
foreach (DataGridViewRow row in b1.DataGridView1.SelectedRows)
{
string value = row.Cells[4].Value.ToString();
double currentCellValue = 0.0;
if(double.TryParse(value , out currentCellValue)
{
totalCost += currentCellValue;
}
}
TotalCost.Text = totalCost .ToString();

Row index provided is out of range. Parameter name: index

I trying to move selected items from one gridview to another gridview, when the user has selected items(more than one item). It reads the first row and third row item in gridview and sends it to gridview2.
Gives me the above error in try catch. How do I read each row by row without jumping to read to the third row when user has selected a second row. I have been working on this for a week now. I am a beginner in C#. Thanks in advance.
// dgSubjectGridView2 is cleared, first Gridview(dgSubjectGridView) is moving selected item from its grid to dgSubjectGridView2
private void btnGo_Click(object sender, EventArgs e)
{
dgSubjectGridView2.Rows.Clear();
try
{
DataGridViewRow row = new DataGridViewRow();
//Counts the total number of rows in dgSubjectGridView
for (int i = 0; i < dgSubjectGridView.Rows.Count; i++)
{
row = dgSubjectGridView.Rows[i];
Boolean checkstate;
checkstate = Convert.ToBoolean(row.Cells[0].Value);
foreach (DataGridViewRow item in dgSubjectGridView.Rows)
{
if (checkstate == true)
{
dgSubjectGridView2.Rows.Add(false, item.Cells[1].Value.ToString());
dgSubjectGridView.Rows.RemoveAt(row.Index);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//End
}
}
It seems that you are twice looping through the same GridView row collection. Replace your try block with the following code and see if it produce the desired result.
try
{
foreach (DataGridViewRow row in dgSubjectGridView.Rows)
{
Boolean checkstate = Convert.ToBoolean(row.Cells[0].Value);
if (checkstate == true)
{
dgSubjectGridView2.Rows.Add(false, row.Cells[1].Value.ToString());
dgSubjectGridView.Rows.RemoveAt(row.Index);
}
}
}

Populating listview through runtime in C#

I am creating a listview and the items and subitems are being fetched from the database. However, when I'm running my solution the listview only displays the id. I want to dynamically add columns and rows to make it like a datagrid. here's my code.
private void frmMain_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table = logic.ViewInfo();
listView1.View = View.Details;
ListViewItem myList;
foreach (DataRow row in table.Rows)
{
myList = new ListViewItem();
for (int i = 0; i < row.ItemArray.Length; i++)
{
if (i == 0)
myList.Text = row.ItemArray[i].ToString();
else
myList.SubItems.Add(row.ItemArray[i].ToString());
}
listView1.Items.Add(myList);
}
}
The reason you see only an ID is that you don't have proper columns.
You can add them in designer or in a code.
As you need it to be added "dynamically", you need to add as many columns, as values you have in an ItemArray.
Try this code. It is working for me.
There is no need in using Text property. Each SubItem stands for a cell.
private void frmMain_Load(object sender, EventArgs e)
{
DataTable table = logic.ViewInfo(); // Combine declaration and assignment
listView1.View = View.Details; // Better place it in designer
listView1.Columns.Clear();
foreach (var column in dataTable.Columns)
{
listView1.Columns.Add(column.ColumnName); // or Caption, or anything else
}
foreach (DataRow row in table.Rows)
{
ListViewItem myList = new ListViewItem(); // Move declaration into inner scope. You are reinitializing reference type variable each type. In my opinion, it is not good.
for (int i = 0; i < row.ItemArray.Length; i++)
{
// You don't need Text property
myList.SubItems.Add(row.ItemArray[i].ToString());
}
listView1.Items.Add(myList);
}
}

C# DataGridRow.Rows Selects the new row

I have a simple function in my program that selects the current cell, then it (FillsDown) copies the current cell into ALL the cells below it.
However my simple function places the value in the Row at the bottom which is the new row and I do not want the value to be populated here.
Heres the current code. (Where COLINDEX is just the column im referring to in my grid)
string replacestring = row.Cells[COLINDEX].Value.ToString();
foreach (DataGridViewRow row in dataGrid1.Rows)
{
if (row.Index > startrow)
{
row.Cells[COLINDEX].Value = replacestring;
}
}
Is there a simeple method/property I can check against so I dont accidently populate the last row ?
My example below uses a fake property (.Exist)
foreach (DataGridViewRow row in dataGrid1.Rows)
{
if ((row.Index > startrow) && row.Exist)
{
row.Cells[COLINDEX].Value = replacestring;
}
}
DataGridViewRow has a property called IsNewRow
And try to walk the Rows collection using the index
for(int x = startRow + 1; x < dataGrid1.Rows.Count; x++)
{
DataGridViewRow row = dataGrid1.Rows[x];
if (row.IsNewRow == false)
{
row.Cells[COLINDEX].Value = replacestring;
}
}

C# DataGridView.Rows.ToString()

I am trying to store the values of each of my rows in a string.
If I try to do DataGridView.Rows.ToString() I get
System.Windows.Forms.DataGridViewRowCollection
Not even close to what I need.
Any ideas?
I think you're looking for something on a per row basis. If so, I suggest the following.
private static IEnumerable<string> GetRowValues(this DataGridView dgv)
{
var list = new List<string>(dgv.Rows.Count);
foreach (DataGridViewRow row in dgv.Rows)
{
var sb = new StringBuilder();
foreach (DataGridViewCell cell in row.Cells)
{
sb.Append(cell.ToString());
}
list.Add(sb.ToString());
}
return list.AsReadOnly();
}
You need to do something like this:
StringBuilder sb = new StringBuilder();
for(int row=0; row<DataGridView.Rows.Count; row++)
{
for(int col=0; col < DataGridView.Columns.Count; col++)
{
sb.Append(DataGridView.Row[row][col].ToString());
}
}
sb.ToString(); // that will give you the string you desire
EDIT I didn't run this through to check that it runs but it should at least give you a starting point. Also, this will give you all rows. If you want just one row, change the variable row to the row number you need (keep in mind that it is zero-based).
Use the for each statement to iterate through each row in the Datagridview.
foreach (DataGridViewRow datarow in dataGridView.Rows)
{
string col1 = datarow.Cells["Col1"].Value.ToString();
string col2 = datarow.Cells["Col2"].Value.ToString();
string col3 = datarow.Cells["Col3"].Value.ToString();
}
Foreach(Var row in DataGridView.Rows)
{
Foreach(Var cell in row.Cells)
{
Var str = cell; // this is the string you want
}
}
Something like the code above. Excuse the formatting typed on iPad.

Categories

Resources