DataGridView in C# - 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.

Related

"DataGridView.Columns[i].Name" Empty for last column

I have created a windows form application using C#.
I am trying to loop at the columns/cells and populate the column names as cell values. (Just for 1st row)
It works fine for all cells, except the last cell. That is, in the displayed data grid, all cells except the last cell has their corresponding column names.
I am unable to point out what's happening.
When I access 'DataGridView.Columns[i].HeaderText' for the last cell it returns the correct header text.
But When I access 'DataGridView.Columns[i].Name' for the last cell, it is empty.
I have also verified the bound column properties and can confirm that it matches what I have for the other columns.
Please find below my code:
for (int i=0;i< DataGridView.Columns.Count;i++)
{
fieldName = DataGridView.Columns[i].Name.Replace("_filter", "");
if (!String.IsNullOrEmpty(DataGridView.Columns[i].Name))
{
DataGridView.Rows[0].Cells[i].Value = DataGridView.Columns[i].Name + i;
}
else
{
DataGridView.Rows[0].Cells[i].Value = DataGridView.Columns[i].HeaderText;
}
}
Any help is much appreciated.
Below is screenshot of my BoundColumns screen
Bound Columns Screen:
Below is screeshot of my output, showing the last column
Final Output. The Email ID column is expected to have the column name, not the column text

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.

all value in gridview

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);
}

How to find column count in a TableHeaderRow with only table id?

I have a situation where I want to make a generic codebehind function to show a message row that spans the whole table. I have previously passed the Table object and the number of columns so that it could set the column span, but this is somewhat error prone as we sometimes add new columns and I have to update the column count numbers for the messages.
There doesn't seem to be any column count in the Table object and neither any way to get the TableHeaderRow that has been added in the aspx file. I'd like to avoid having to add id's to all the TableHeaderRow's as well.
Try this, should work (assuming the TableHeaderRow is the first child of the Table):
int j = 0;
foreach (Control current in tableId.Controls[0].Controls)
{
if (current.ToString() == "System.Web.UI.WebControls.TableHeaderCell")
{
j++;
}
}

How to select row in Telerik RadGrid?

When user select a row in Telerik Rad Grid, i want to take fields in this row. how to do this?
It's a little tricky, but easy after you've done it once.
Step 1.
Go to the Radgrid itself and edit the field DataKeyNames="" (under MasterTableView) and add the datafield you are pulling:
<MasterTableView ... DataKeyNames="ColumnNameFromSqlGoesHere">
Step 2.
Decide how you are going to grab the values, on Row Change (SelectedIndexChanged) or on a buttong press with a command attached to it (ItemCommand).
If row change, per your question:
protected void RadGrid1_SelectedIndexChanged(object sender, EventArgs e)
{
var z = RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["ColumnNameFromSqlGoesHere"];
}
This will assign the variable "z" to the value of the column you have chosen (ColumnNameFromSqlGoesHere) at that given row.
If you wish to select multiple variables every time you change row you need to add all the values you wish to select under the DataKeyNames=" ". (Seperated by commas). You would then fetch each value via the code seen in the SelectedIndexChanged method:
var a = RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["SecondColumnGoesHere"];
var b = RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["ThirdColumnGoesHere"];
Etc... You get the idea.
This should get you going. It is a solution straight from Telerik: Retrieving primary key values for selected items
Try this. This may help you.
STEP 1:Add one radiobutton column in the radgrid
STEP 1: Get the primary key of selected row in the radgrid.
int primaryKey =0;
RadioButton radioButton;
for (int i = 0; i < RadGrid1.Items.Count; i++)
{
radioButton = RadGrid1.Items[i].FindControl("rdSelect") as RadioButton;
If (radioButton.Checked)
{
primaryKey = RadGrid1.MasterTableView.Items[e.Item.ItemIndex]["ID"].Text;
}
}
Line in the if condition will be used to get the fields from the selected row just by changing the fields datakey name i.e. changing "ID" to other field
Read this article for more details...
http://codedotnets.blogspot.in/2012/01/get-primary-key-selected-radiobutton.html

Categories

Resources