DataGridView Copy Paste Multiple Columns - c#

I was wondering if someone could help me. I have wrote some some code that will copy from the Clipboard into a DatagridView. The issue that I am having is that everything works as it is suppose to except the first cell.
For Example if I copy from Excel 2 columns only one row the value of 20 in the first column and the value of 30 in the second column
Then when I paste it in the DataGridView I get the following.
In the first column I get the number 20 and then a large space and the the value of 30 but in the second column only the value of 30 shows up.
Below is my code id anyone has an idea on how to fix that first cell please help me
if (e.Control && e.KeyCode == Keys.V)
{
char[] rowSplitter = { '\r', '\n' };
char[] columnSplitter = { '\t' };
//get the text from clipboard
IDataObject dataInClipboard = Clipboard.GetDataObject();
string stringInClipboard = (string)dataInClipboard.GetData(DataFormats.Text);
//split it into lines
string[] rowsInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);
//get the row and column of selected cell in grid
int r = DGV.SelectedCells[0].RowIndex;
int c = DGV.SelectedCells[0].ColumnIndex;
//add rows into grid to fit clipboard lines
if (DGV.Rows.Count < (r + rowsInClipboard.Length))
{
MessageBox.Show("PasteValues Will be Outside of Grid");
return;
}
// loop through the lines, split them into cells and place the values in the corresponding cell.
for (int iRow = 0; iRow < rowsInClipboard.Length; iRow++)
{
//split row into cell values
string[] valuesInRow = rowsInClipboard[iRow].Split(columnSplitter);
//cycle through cell values
for (int iCol = 0; iCol < valuesInRow.Length; iCol++)
{
//assign cell value, only if it within columns of the grid
if (DGV.ColumnCount - 1 >= c + iCol)
{
DGV.Rows[r + iRow].Cells[c + iCol].Value = valuesInRow[iCol];
for (int i = 0;
i < selectedCellCount; i++)
{
DGV.SelectedCells[i].Value = valuesInRow[iCol]; ;
}
}
}
}
}

Related

With Xamarin ... How do I SUM two cells inside the grid for the same row or for several rows?

Please help, as I made a small project with Xamarin
It is a connection to a SQl server database and then filling the Datatable with data and then displaying the data in Grid .. which contains Entries that have been added programmatically and not in XAML ... This means that Entries do not have Names or IDs assigned to each one of them .. Even these At the moment it is working fine...and the data is being recalled properly
But as you know inside Grid there are Rows and Columns and I need to add or multiply the contents of Entries in the same row or add the contents of a column or columns
How do I SUM two cells inside the grid for the same row or for several rows?
And does the grid fit with that or do I have to choose another rendering too
Notes ::: >>> Maingrid is my Grid
////// define the number of rows according to the number of item you have
for (int i = 0; i < dt.Rows.Count; i++)
{
MainGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
}
//////// defining column number (in this case 3)
for (int j = 0; j < dt.Columns.Count; j++)
{
MainGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
}
////////// adding the items to the grid (3 column , RN rows)
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int num = 0; num < dt.Columns.Count; num++)
{
Entry entry = new Entry();
entry.Text = dt.Rows[i][num].ToString();
entry.TextColor = Color.Blue;
entry.BackgroundColor = Color.GhostWhite;
entry.HorizontalOptions = LayoutOptions.FillAndExpand;
entry.HorizontalTextAlignment = TextAlignment.Center;
entry.VerticalTextAlignment = TextAlignment.Center;
entry.Keyboard = Keyboard.Numeric;
entry.TextChanged += MyEntry_TextChanged;
entry.WidthRequest = 50;
MainGrid.Children.Add(entry, num , i);
}
You can get the two cells at first. And then get the sum of the two cell and set it as another cells value.
You can try the following code:
public void GetSum()
{
var rowcount = MainGrid.RowDefinitions.Count;
for( int i = 0; i < rowcount; i++ )
{
Entry A = (Entry)MainGrid.Children.Where(view => Grid.GetRow(view) == i && Grid.GetColumn(view) == 0 ).FirstOrDefault();
Entry B = (Entry)MainGrid.Children.Where(view => Grid.GetRow(view) == i && Grid.GetColumn(view) == 1 ).FirstOrDefault();
Entry C = (Entry)MainGrid.Children.Where(view => Grid.GetRow(view) == i && Grid.GetColumn(view) == 2 ).FirstOrDefault();
C.Text = (int.Parse(A.Text) + int.Parse(B.Text)).ToString();
}
}
The code above can make your MainGrid like a grid in the picture below:
In addition, the point is this line MainGrid.Children.Where(view => Grid.GetRow(view) == i && Grid.GetColumn(view) == 0 ).FirstOrDefault(). You can use it to get any child in the grid if you know the child view's row index and column index.

Can you set/reverse the starting index of the DataGridView rows?

I am creating a WPF form that requires a data table to represent different cell statuses using colors. I am using a DataGridView and creating cells depending on what file I decide to upload. The configuration for the data table is represented in 2 different types of files: a .xml and a .prd file. The .xml file is properly represented in the table since the rows and columns start at the correct point. The .prd file assigns the last row in the table as the first row.
eg. The .xml file has row[0] as row[0], but the .prd file has row[24] as row[0].
I need the DataGridView to not just represent the data, but also visually depict how the orientation is supposed to look. I just can't seem to figure out how to reverse the rows index.
Here is my code for the creation of the DataGridView for both types of files:
private void GenerateDataGridView(DataGridView dgv, int rows, int columns)
{
if (XMLSelected == true)
{
for (int j = 0; j <= rows; j++)
{
if (j == 0)
dgv.Columns.Add(null, null);
else
dgv.Columns.Add("rows" + j, "row " + j);
}
for (int i = 0; i <= columns; i++)
{
dgv.Rows.Add("column " + i);
}
XMLSelected = false;
}
else if(PRDSelected == true)
{
for (int j = 0; j <= rows; j++)
{
if (j == 0)
dgv.Columns.Add(null, null);
else
dgv.Columns.Add("rows" + j, "row " + j);
}
for (int i = 0; i <= columns; i++)
{
if (columns - i > 0)
{
dgv.Rows.Add("column " + (columns - i));
}
}
PRDSelected = false;
}
}
Just an FYI, the row headings are actually "columns 1,2,3..." and the column headings are "row 1, 2, 3..." so, for the .prd file, I need the "columns" to start from the highest value both in text and index from the top and decrease as it creates each row.

align columns headers with cells values in a text file that exported from a datagridview in c#

I export my data from a DGV and align them with a space delimiter and it is working good for me. i also export the headers before the cells values. the thing that i want to do but i can not is aligning and adjusting the cells with headers to see them as a table that its members are separated by a delimiter (here space). my means is i want to see cells values right below the headers (if they have smaller or equal lengths) and headers text right on the top of the cells values if header length is less than cells values lengths), in the other word, Keeping cells values and their related headers together.
thanks in advance.
What i have been tried:
int RowsCount = DataTable.Rows.Count;
int ColumnsCount = DataTable.Columns.Count;
var newline = System.Environment.NewLine;
var delimiter = " ";
var copied= new StringBuilder();
List<int> clmnLocation = new List<int>() {};
string header = "";
for (int c = 0; c < DataTable.Columns.Count; c++)
{
header = header + Convert.ToString(DataTable.Columns[c].ColumnName).Replace(" ", "") + delimiter;
//Count header length to get the padright() value and put in a list<int>
clmnLocation.Add(header.Length);
}
// Export titles:
for (int c = 0; c < DataTable.Columns.Count; c++) copied.Append(Convert.ToString(DataTable.Columns[c].ColumnName).Replace(" ","") + delimiter);
//Append A Line After Header.
clipboard_string.Append(newline);
//Cells
for (int i = 0; i <RowsCount; i++)
{
for (int j = 0; j <ColumnsCount; j++)
{
if (j > 0)
copied.Append(DataTable.Rows[i][j].ToString().PadRight(clmnLocation[j]) + delimiter);
else
copied.Append(DataTable.Rows[i][j].ToString() + delimiter);
}
copied.Append(newline);
}
WordDoc.Content.Text = copied.ToString();

checking excel row values and return column header in c# winforms

I currently have program that checks a date that is selected in MonthCalendar and uses it to search through the first column [date] for a matching value before performing a function. This function is to check the rest of the columns among the same row for a certain Value and then returning the column headers that have that Value. How do I do this?
private void button1_Click(object sender, EventArgs e)
{
string date = monthCalendar1.SelectionRange.Start.ToShortDateString();
string CSVFilePathName = #"pathname.csv";
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt5 = new DataTable();
for (int i = 0; i < Cols; i++)
dt5.Columns.Add(Fields[i].ToLower(), typeof(string));
DataRow Row;
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt5.NewRow();
for (int f = 0; f < Cols; f++)
Row[f] = Fields[f];
dt5.Rows.Add(Row);
}
for (int i = 0; i < 29; i++)
{
Object o = dt5.Rows[i]["date"];
if (o.ToString() == date)
{
(INSERT CODE HERE TO CHECK REST OF COLUMNS ON SAME ROW AND RETURN COLUMN HEADER)
}
}
}
Hi I have now attached the code
You can use Microsoft Excel Interop or ClosedXML to read an excel file and then search for whatever you want.
You've said that you already have a program that does something. Can you post the code or whatever you've tried so far? It'll help us help you better.

Populating a listbox in c#

I have a listbox and I manage to bind the Excel worksheet to the list box (after hours of researching on the Internet).
Now I need to read the values from the sheet into the listbox, but unable to locate any suitable solution.
This is what I have done so far:-
private void LoadExcelSheet(string path, int sheet){
_Application excel = new Excel.Application();
Workbook wb;
Worksheet ws;
int row = 0;
int col = 0;
wb = excel.Workbooks.Open(path);
ws = wb.Worksheets[sheet];
for (row = 1; row < 10; row++){
for (col = 1; col < 6; col++){
listBox1.Items.Add(ws.Cells[row, col].Value2);
}
}
}
//------------------ end of LoadExcelSheet---------------------------
this only display 1 row with each item of data on top of each other eg:-
aaaaaaaa
bbbbbbbb
cccccccc
dddddddd
instead of: aaaaaaaa bbbbbbbb cccccccc dddddddd
Thanks in advance..
The issue is with your for loops, try this:
for (var row = 1; row < 10; row++)
{
string r = "";
for (var col = 1; col < 6; col++)
{
r += " " + ws.Cells[row, col].Value2;
}
listBox1.Items.Add(r.Trim());
}
You are populating the list box inside a loop containing the columns, try something like
for (row = 1; row < 10; row++){
string a = "";
for (col = 1; col < 6; col++){
a += ws.Cells[row, col].Value2+" ";
}
listBox1.Items.Add(a);
}
Let's split the problem
Data collection
Collected data representation
Data collection (with a help of Linq):
using System.Linq;
...
string[] data = Enumerable
.Range(1, 9) // 9 rows, starting from 1
.Select(row => string.Join(" ", Enumerable // cols are joined with space
.Range(1, 5) // 5 columns in each row
.Select(col => ws.Cells[row, col].Value2)))
.ToArray();
And data representation (as ListBox items):
listBox1.Items.AddRange(data);

Categories

Resources