datagridView.rows.count = 0 - c#

i know this question maybe a duplicate of others, but i'm losing my mind trying to understand what's going on.
This program of mine loads a list of excel files, and when one of them i selected, i can choose which sheet i want to display with the datagridview.
Now, having data_ListDisplay as DatagridView populated with 211 rows:
With the code below, i would like to find the colum.index of the first cell in row collection in datagridview which has the given "string" that matches with the search criteria.
However, the row.count is ALWAYS = 0.
Yesterday it was working fine (OFC it was..). Then, i needed to make the datagridview PUBLIC to use the data inside to populate another list (data is elaborate while populating) which belongs to another class.
Code is fine, no error and the line i used to make data_listDisplay puplic is
public DataGridView DataGridCR { get { return data_ListDisplay; } }
Hereafter the piece of code (in the original code, the 2 foreach construct belongs to 2 private methods that calculates the variables CrAnalysedCol and CrRealisedCol. I put them in the same method to be fast in copy/paste here)
private void cbo_List_SelectedIndexChanged(object sender, EventArgs e)
{
//Fill data_ListDisplay with the data set (datagridview) by changing the combobox value
dt = tablecollection[this.cbo_List.SelectedItem.ToString()];
data_ListDisplay.DataSource = dt;
label3.Text = ($"Column Count{data_ListDisplay.Columns.Count}/Row Count {data_ListDisplay.Rows.Count}"); //Debug Purpose
foreach (DataGridViewRow row in data_ListDisplay.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value.ToString().Contains("CR to validate"))
{
CrRealisedCol = cell.ColumnIndex;
}
}
}
foreach (DataGridViewRow row in data_ListDisplay.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value.ToString().Contains("CR analysed"))
{
CrAnalysedCol = cell.ColumnIndex;
}
}
}
}
where:
cbo_List is a combobox which is filled with all sheets in the workbook selected and both CrAnalysedCol and CrRealisedCol are declared as public as well.
label3.Text is always correct with both column and rows count.
Can someone please help me on that?
Thanks in advance
EDIT 05/03/2020
It look like that when i try to access to the DataGridView from another class by using
Form_VVTool formmain = new Form_VVTool();
dt becomes = null.
I suppose that it is because of InitializeComponent() which is called everytime the above code is executed.
What could be a way to preserve everything from Form_VVTool?
Thanks again

Related

Is there a way to implement DataGridView SaveItem button without using TableAdapters?

I'm currently trying to implement DataGridView SaveItem operation...
Since I already have CRUD methods written and I didn't use TableAdapters I'm wondering if there is a smart way of implementing Save without using adapter.
My current take was implementing on CellEditEnd ike this:
private void djelatnikDataGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow gridrow = djelatnikDataGrid.Rows[e.RowIndex];
DataRowView rowview = (DataRowView)gridrow.DataBoundItem;
DataRow row = rowview.Row;
if (row.RowState != DataRowState.Unchanged || djelatnikDataGrid.IsCurrentRowDirty)
{
if (djelatnikDataGrid.Rows.Count == (e.RowIndex+1))
{
djelatnik_ListaNovihRedaka.Add(row);
}
djelatnik_ListaRedakaSaPromjenama.Add(row);
}
}
I want to check if the record is a new row or existing one that was edited, then I add it to NewRowList or UpdatedRowList based on RowIndex and on SaveItemClick I go foreach row and call Insert/Update methods like this:
private void btnSaveDjelatnik_Click(object sender, EventArgs e)
{
if (DataDirty)
{
foreach (DataRow row in djelatnik_ListaNovihRedaka)
{
Djelatnik djelatnik = new Djelatnik();
djelatnik.ImePrezime = row["ImePrezime"].ToString();
djelatnik.Zvanje = row["Zvanje"].ToString();
djelatnik.RadnoMijesto = row["RadnoMjesto"].ToString();
r.InsertDjelatnik(djelatnik);
}
if (vozilo_ListaRedakaSaPromjenama.Count > 0)
{
foreach (DataRow row in djelatnik_ListaRedakaSaPromjenama)
{
Djelatnik djelatnik = new Djelatnik();
djelatnik.ImePrezime = row["ImePrezime"].ToString();
djelatnik.Zvanje = row["Zvanje"].ToString();
djelatnik.RadnoMijesto = row["RadnoMjesto"].ToString();
r.UpdateDjelatnik(djelatnik);
}
}
MessageBox.Show("Promijene su spremljene u bazu podataka!");
}
}
I know it's kind of ambiguous question but If somebody could point me to a direction I'd appreciate it
I decided to implement Add/Edit form for inserting or editing new records.
Edit form opens on double clicking the record and add form has AddItem button
This will save me a lot of time and trouble...
Thanks for suggestions anyway ~ ChenChi
There's another way. You can delete all related records in database and then reinsert all data in you grid to DB. so you don't need to know which is new/existing. It will help you less calculation and steps...
Don't forget use Transaction for deleting and reinserting.
Use a Dictionary(Of DataGridView, Boolean) oDic_RowToWasEdited for your Rows.
As soon as you update your DataGridviews DataSource put each Row into the Dictionary with the Value False. Whenever a Cell gets edited change the rows dictionary entry to true.
As soon as you want to save to the Database check first if your dictionary contains the row. If not it means you have a new Row. If the dictionary contains that key check its value. If it's true you know that you have to update it.
Althrough I'm sure there a better ways of doing so using the datatables RowState attribute, I think this should get you going.

Get value of a selected checkbox row in DatagridView

I have a DatagridView which contains row and data. I've added checkboxs to select one of the row (1) and then generate a PDF with the data of the selected row (2) (see picture) :
My code contains a part which check if checkbox is 1 or 0 and then I don't know how to get the data of the "checked row".. See
private void button_generer_pdf_Click(object sender, EventArgs e)
{
List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGrid_factures.Rows)
{
if (Convert.ToBoolean(row.Cells[column_action.Name].Value) == true)
{
MessageBox.Show("OK!"); // Just to check if it undestands I've checked the row
//And then here I want to get highlighted data on the screenshot to create my Pdf
}
}
//PDF Generation here
The same way you got the data from your selection column "row.Cells[column_action.Name].Value" by changing it to be the right name so maybe
row.Cells["NOM"].Value
or you can use the array number should you know it eg
rows.Cells[3].Value
hi my friend you can use this code for any cell or use a loop for all cells!!!
public void ReadDataFromDataGridView()
{
string value = dataGridView1.SelectedRows[0].Cells["columnName"].Value.ToString();
}

Read data from a DataGridView Cell and store it into a ListView

I'm a little bit overwhelmed. I have a DataGridView with a table which consists of five columns. Now when one or more row(s) are selected by the user and I click a Button I want to store two elements of these selected rows in a ListView. How to do that? Sorry for posting no code but I really don't know how to start with this (except for a foreach loop). Is there a way to get the cell value by the column name? Thanks!
EDIT:
I have some code for the beginning but it's completely wrong i guess...
using (SqlConnection connection = new SqlConnection(connectionQuery))
{
foreach (DataGridViewRow row in dataGridView4.SelectedRows)
{
foreach (DataGridViewColumn col in dataGridView4.Columns)
{
if (col.Name == cusIdBox.Text)
{
//DO
}
if (col.Name == cusNameBox.Text)
{
//DO
}
}
}
Ok thanks I've got a solution:
foreach (DataGridViewRow row in dataGridView4.SelectedRows)
{
cusId = row.Cells[cusIdBox.Text].Value.ToString();
cusName = row.Cells[cusNameBox.Text].Value.ToString();
cusIdCells.Add(cusId);
cusNameCells.Add(cusName);
}

How to get IDs of only checked rows of a datagridview

I have a datagridview that contains list of subjects populated from Subject table from database.Columns include
Select(checkbox),
SubjectId,
SubjectName,
SubjectGroup.
Now I want if a user Selects on any of the desired rows, the corresponding SubjectId's should be added to a List. I have made and inserted into the desired table in the database.
The problem is that the new column of checkboxes I have added to this datagridview is not being detected.
My code is:
foreach (DataGridViewRow row in gvSubjectsOpted.Rows)
{
if (Convert.ToBoolean(gvSubjectsOpted.SelectedRows[0].Cells["SelectId"].Value=true))
{
olist.Add(gvSubjectsOpted.SelectedRows[0].Cells["SubjectId"].Value.ToString());
}
}
Late to the party. I had the same issue with trying to get the checkbox column by name, use the index instead. Here is a linq example assuming the checkbox is column 0 and the stored values for TrueValue and FalseVale are true and false respectively.
var checkedRows = from DataGridViewRow r in gvSubjectsOpted.Rows
where Convert.ToBoolean(r.Cells[0].Value) == true
select r;
foreach (var row in checkedRows)
{
olist.Add(row.Cells["SubjectId"].Value.ToString());
}
I realise this is an old post but I came across it and didn't think it was really answered in an efficient way so I thought I would add my method.
I have a similar block in my windows app. I read the values from the grid when the user clicks a button, and I want to know which rows they checked. As the checkboxes are in Cell 0 and the data I want is in Cell 1, I use the following code. Note the cast: it is important as it allows us the use the Where clause and therefore just a single line of code to get the collection of data. I could use the name of the cells instead of magic index numbers but then it would not fit your app so I put numbers instead (you should use names)
var checkedRows = dataGridView
.Rows
.Cast<DataGridViewRow>()
.Where(x => x.Cells[0].Value.ToString() == "1")
.Select(x => x.Cells[1]);
Note that this will give you an IEnumerable of type DataGridViewCell. If you want you can either add something like .Value.ToString() to the select or do this when you use your collection.
You question is similar to another SO question.
Check the answer of this Datagridview checkboxcolumn value and functionality.
Try this
foreach(GridViewRow r in gvSubjectsOpted.Rows)
{
GridViewCheckBoxColumn c = r.cells[0].Controls[0] as GridViewCheckBoxColumn;
if(c.Checked)
{
//Do something.
}
}
private void button1_Click(object sender, EventArgs e)
{
string subjId;
List<string> lines = new List<string>();
for (int i = 0; i < gvSubjectsList.Rows.Count; i++)
{
bool Ischecked =Convert.ToBoolean(gvSubjectsList.Rows[i].Cells["Select"].Value);
if (Ischecked == true)
{
subjId = gvSubjectsList.Rows[i].Cells["SubjectId"].Value.ToString();
lines.Add(subjId);
}
}
comboBox1.DataSource = lines;
}
//the most important thing is to set 'true' and 'false' values against newly added checkboxcolumn instead of '0' and '1'...that is,
CBColumn.FalseValue = "false";
CBColumn.TrueValue = "true";

DataGridView: Add Data Programatically on Specific Cells

I'm currently trying to add data programatically onto a DataGridView, but it doesn't seem to be working.
What I have is an Array, which I fill from a text file:
public static string PathList = #"C:\Users\gbbb\Desktop\Pfade.txt";
_PathRows = System.IO.File.ReadAllLines(#PathList);
and I have a DataGridView with 4 Columns on which I add as many Rows as I have paths, so:
public void InitPathsTable()
{
TabelleBib.Rows.Add(_PathRows.Length);
//And here is where i want to add the Paths on Column Nr.4
}
Next what I need is a way to add all paths that I get (24) into the Column Nr.4,
one Path per Row.
But it seems to be nearly impossible for a beginner like me, so I am asking you.
This is method that will do that for you. Read comments (especially make sure you have added 4 columns to you DataGridView):
public void InitPathsTable()
{
int rowindex;
DataGridViewRow row;
foreach (var line in _PathRows)
{
rowindex = TabelleBib.Rows.Add(); //retrieve row index of newly added row
row = TabelleBib.Rows[rowindex]; //reference to new row
row.Cells[3].Value = line; //set value of 4th column to line. WARNING: TabelleBib has to have 4 columns added either from code or designer othwerwise here you will get exception
}
}
if you get any more problems, write a comment and I will come back to you :)

Categories

Resources