all value in gridview - c#

I have a grid view table populated using a stored procedure. The grid view table loads and works fine. The problem I am having is how to get all the values in a particular column.
So far, I can only get the value of the 1 column and cell. I need all the values in that column for each row. Numbers of value varies depending on the parameters user set.
code is in c#. This gets me the first column, first row.
gridviewID.DataSource = cmd.ExecuteReader();
gridviewID.DataBind();
TxBx.Text = gridviewID.Rows[0].Cells[0].Text;

You can use for each loop to get all the rows within the grid view.
IList<string> parameters = new List<string>();
foreach (GridViewRow row in AdminSearchGridView.Rows)
{
parameters.Add(row.Cells[0].Text);
}

Related

How to INSERT added rows and UPDATE edited ones in a DataGridView?

I have a Form that shows information about a purchase and within this form I have a DataGridView whose columns are dynamically generated based on a table on the database. This DGV contains information about the items in the selected purchase.
Here's an example of how I generate the columns in runtime in an existing DataGridView:
foreach (ColumnDGV columnDGV in columnsDGV)
{
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = columnDGV.A02_CAMPO;
col.HeaderText = columnDGV.A02_TITULO;
col.DataPropertyName = columnDGV.A02_CAMPO;
this.dataGridView.Columns.Add(col);
}
The object ColumnDGV contains information about the column to be created.
Then I select the columns' names from the columns list and perform the sql query based on those columns:
private void CarregarConteudoDGV()
{
SolicitCompraBLL solicitCompraBLL = new SolicitCompraBLL();
// Gets the columns' names to be used in the SELECT statement.
List<string> columnsNames = this.CamposDGV.Select(c => c.A02_CAMPO).ToList();
// Returns a DataTable containing the items of the selected purchase.
this.dataGridView.DataSource = solicitCompraBLL.ObterItensSolicitacao(columnsNames, this.B11_NUM);
}
When the user clicks in the save button I just iterate through all rows in the DGV and add its values to a nested List where each item is a list of string[2], where the position 0 contains the column name and position 1 its value. Then I pass this List to a method that creates the sql command to update the records.
I can already save the changes of each item in the database, but I also have to insert the added items. How do I know which items should be inserted and which ones should be updated?
When you insert an object in DataBase, generally your object don't have yet an Id. The object to be update must have their Id's existing yet. Now you should see if the object has an Id or Not. If the Id is Zero (or does not exist) then you insert it, otherwise you update it.

C#, Delete first row from gridview element

This has been asked many times, but I can't seem to find a direct answer.
Using C#, I use a datatable to fill a gridview. The first row of my datatable contains the table headers, so I loop through that row and fill the gridview header row. But now I need to get rid of that first row (the header row) in the table. I've looked all over, and all sources agree that the correct syntax is:
strSQL = "SELECT * FROM [Station ID Request$]";
OleDbDataAdapter adaBatch = new OleDbDataAdapter(strSQL, strConnExcel);
DataTable dtBatch = new DataTable();
adaBatch.Fill(dtBatch);
gv_stations.DataSource = dtBatch;
gv_stations.DataBind();
// Fill gridview headers with first row of data (spreadsheet headers)
int i = 0;
foreach (DataColumn col in dtBatch.Columns)
{
gv_stations.HeaderRow.Cells[i].Text = dtBatch.Rows[0][i].ToString();
i++;
}
// Remove the first line of the gridview (contains header info)
gv_stations.DeleteRow(0);
Everything works but the last line, which gives me this error:
System.Web.HttpException (0x80004005): The GridView 'gv_stations' fired
event RowDeleting which wasn't handled. at
System.Web.UI.WebControls.GridView.OnRowDeleting(GridViewDeleteEventArgs e)
at System.Web.UI.WebControls.GridView.HandleDelete(GridViewRow row, Int32
rowIndex) at System.Web.UI.WebControls.GridView.DeleteRow(Int32 rowIndex)
Every resource I've tried says that last line should be OK. Can anyone tell why I'm getting that error?
EDIT: Here is my gridview object, as requested.
<asp:GridView ID="gv_stations" runat="server"
AutoGenerateColumns="True"
CssClass="c_gvv c_gvv_stations_results"
style="white-space:nowrap;">
</asp:GridView>
Having read through your comments to other answers I'm a little confused as to what you're saying the problem is. Is it that if you simply bind to the gridview the first row in the data table (headers) appears as both the header row and the first row of data in the gridview?
It seems odd that if you don't want the header row that you first retrieve it and then go through the hassle of adding it all with your foreach loop only to then try and remove it.
If you don't want the header row selected in the first place you can amend your connection string (presumably strConnExcel?) to include "HDR=No", which will stop it from bringing back the first row in the first place.
However, if you want the header row then use "HDR=Yes" and simply bind to your gridview. It will know what the header row is. Looking at what you're doing though it looks like your trying to add the header row and then delete it!?
You are trying to delete a row from GridView rather you should delete it from DataTable. Use this line:
dtBatch.Rows[0].Delete();
Instead of this:
gv_stations.DeleteRow(0);
You can also simply your loop:
for(int i = 0; i < dtBatch.Columns.Count; i++)
gv_stations.HeaderRow.Cells[i].Text = dtBatch.Rows[0][i].ToString();
Complete code:
...
//Fill gridview headers with first row of data (spreadsheet headers)
for(int i = 0; i < dtBatch.Columns.Count; i++)
gv_stations.HeaderRow.Cells[i].Text = dtBatch.Rows[0][i].ToString();
//Remove the first line of the gridview (contains header info)
dtBatch.Rows[0].Delete();
//now do the bindings
gv_stations.DataSource = dtBatch;
gv_stations.DataBind();
You are binding the GridView to a DataSource:
gv_stations.DataSource = dtBatch;
gv_stations.DataBind();
Either remove it from the datasource and then databind, or databind and remove it from the gridview without redatabinding.
Or if you want to keep it there, You can make it invisible:
gv_stations.rows[0].visible=false

Rows in DataRow of Asp.net

Its kind of subjective question to ask but still i hope i will find help.
I was learning about merging two tables from database to a singe DataTable.Then i came accross the following block of code.
DataTable mdt = new DataTable();
mdt.Columns.Add("products");
mdt.Columns.Add("price");
for (int i = 0; i < A.Rows.Count; i++)
{
DataRow dr = mdt.NewRow();
dr["product"] = A.Rows[i]["product"].ToString();
dr["price"] = A.Rows[i]["price"].ToString();
//A is a DataTable
mdt.Rows.Add(dr);
}
I can understand that the datas are being added to the row of a Datatable.
This is what i understood:
The column product of DataTable is assigned a value by dr["product"].Correct me if i am wrong.But how is this A.Rows[i]["product"].ToString(); working.
This should help:
A = DataTable
A.Rows = Collection of DataRows in A
A.Rows[i] = i-th row from collection
A.Rows[i]["product"] = Column "product" in row (return type of expression is object)
So when you do dr["product"] = A.Rows[i]["product"].ToString();, you are assigning the value of the product column of the current row from datatable A to the product column in your new data row. Similarly for the price column.
Rows[i] represents the index to which the value is assigned.I mean for the first loop the value is 0,for second loop the value is 1.So for the firs loop the values of product and price are added to first row with index 0.Similarly for the second loop the values of product and price are added to the second row with index 1.
And for the second part ie ["product"].ToString(),its simply converting the value of product to string.
EDIT
Since A is a Datatable which is already filled.What we are doing with that statement is,we are taking the DataTables's i-th row from the collection,converting it to string and assigning it to the column "product" in the datarow.
The ["product"].ToString() Is taking the value of the cell with the column name product, and converting it to a string to be assigned to your new row.

C# getting values from DataTable or BindingSource

I have a labels that need values retreieved from a Database.
I am able to query the database but how can I extract values from a DataTable and place them in the appropiate labels
Thanks
In DataTable you have rows and columns. To select a particular cell you need to do this:
label1.Text = dataTable[0][0];
This will set the label1 text to Row 0, Column 0 value.
To iterate through each row use:
foreach(DataRow row in dataTable.Rows)
{
Console.WriteLine(row["ColumnName1"]);
Console.WriteLine(row["ColumnName2"]);
Console.WriteLine(row["ColumnName3"]);
Console.WriteLine(row["ColumnName4"]);
}
This will print values for columns against each row. In this code you need to replace string for columnname (e.g. ColumnName1) with your column names
Example of how you retrieve a value from the first row and the column named "MyFirstColumn":
label1.Text = myDataTable.Rows[0]["MyFirstColumn"]

DataGridView in C#

I am using a DataGridView to display some data in my application.
The data in the table gets changed dynamically according to the users input.
I am able to retrieve the data according to the user.
I have to add an extra column named ID and fill in the values serially starting from 1 to the number of rows which are generated dynamically.
I had added the column using dgrid.columns.add("UID");
But how to insert values at runtime?
Seeing your code, it is not correct to do:
dgrid.Columns.Add("UID");
You will have to do:
dgrid.Columns.Add("uidColumn", "UID");
To modify/add the value of an existing cell, if the row already exists, you can do:
dgrid.Rows[0].Cells["uidColumn"].Value = myValue;
That will modify the value of the column with name uidColumn and row 0. According to your problem, all you have to do is:
for (int i = 0; i < dgrid.Rows.Count; i++) {
dgrid.Rows[i].Cells["uidColumn"].Value = GetValueOfRow(i);
}
supposing that you have a method GetValueOfRow that receives a row index and returns the value you need in the ID column in that row.

Categories

Resources