How to get Column Value of a DataRow in a Datatable - c#

I have a DataTable which is bind to dataGridview in my code.
When I get datas from database, the gridview works fine. it fills with data.
What I want to do is getting the primary key value of the specified row.
Ex:
PK Address Phone
1 xxxyyyzzz... 1234567
2 aaabbbccc... 2345678
What I want is this. User will click on any row, then click on a button to add some stuff.
Then I will get PK value, and do other stuffs.
How can I do it?

Hmm can you specify how and when you are talking about getting this value?
You can do this:
int index = dt.Rows.IndexOf(row);
But I am not sure what the point of that would be, if you already have the specified row, why can't you just get the PK via row[columnName]?
But this is more resource intensive than just looping through with a for loop.
Do you need this before or after binding to the dataGridView? If you need to get the value from the dataGridView row that is different.
For your edit:
You would can get the selected row like so:
if (yourDataViewGrid.SelectedRows.Count == 1)
{
Int pk = yourDataViewGrid.Rows[yourDataViewGrid.SelectedRows[0].Index].Cells["PK"].Value.ToString();
}
If you are doing it by some other method like using a checkbox to select a row, you would do this:
foreach (DataGridViewRow row in YourDataGridView.Rows)
{
if ((Boolean)((DataGridViewCheckBoxCell)row.Cells["CheckBoxName"]).FormattedValue)
{
Int pk = rows.Cells["PK"].Value.ToString();
}
}

The DataGridView control binds to a DataTable using the DataView class. You can use something like this to get the DataRow of a DataGridViewRow
var vrow = (DataRowView)grid.Rows[12].DataBoundItem; // get the bound object
var drow = vrow.Row; // the Row property references the real DataRow
where 12 is the index you are looking for. Sometimes it helps to set the DataSource property to a DataView explicitly and keep a reference to it on your form. The view will know the sorting of the data too
var view = new DataView(table);
grid.DataSource = view;

Related

Need to Get data value prior to binding to row in listview

I have a ListView object in Asp.Net (C#) where I also have a ListView_ItemDataBound() method that is populated using a sqlDataSource.
In some cases, I would like to be able to insert a row in the ListView prior to the current record being bound. I.e., as the rows are being populated, I need to be able to read the value that is about to be bound and then insert a "header" row mid stream before the current row of data is added to the ListView.
In the case of the ItemDataBound event, the data seems to be already bound to the control so the rows being added are actually one ListView row too late for me to do anything.
ListView_ItemDataBound()
{
System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
//Pseudo code of what I'd like
//if rowView["some_field"]==123 then
// insert row prior to this row being bound
}
I'm relatively new to Asp.Net and come from a classic asp background so maybe I'm thinking and going about this all wrong. Any suggestions would be appreciated.
Instead of doing that after you've already assigned the datasource and called listView.DataBind() you should do that in the datasource. Presuming it's a DataTable:
List<int> rowIndices = new List<int>();
for(int i = 0; i < dataTable.Rows.Count - 1; i++)
{
int some_field = dataTable.Rows[i].Field<int>("some_field");
if (some_field == 123)
rowIndices.Add(i + rowIndices.Count); // indices will increases by count
}
foreach(int index in rowIndices)
{
DataRow newRow = ....
dataTable.Rows.InsertAt(newRow, index);
}
Now assign this modified table as datasource and call DataBind.

Save added rows in DataGridView to database

I am trying to save a new added row in a DataGridView to a database. I can't understand which method to call - either gridview1_UserAddedRow or gridview1_RowsAdded (what if it's just one row?).. So far, I've seen that gridview1_RowsAdded executes every time when the form loads.
The DataGridView is bound using a BindingList.
This is how the gridview1_UserAddedRow looks like:
private void dataGridView1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
int lastRow = dataGridView1.Rows.Count - 2;
DataGridViewRow newRow = dataGridView1.Rows[lastRow];
bindinglist.Add(new MyTestClass{ ScheduleId = scheduleId, Name = Convert.ToString(newRow.Cells["Name"].Value),
Value = Convert.ToString(newRow.Cells["Value"].Value), TestId = testId});
}
Unfortunately, this doesn't work and nothing is inserted. Actually, I think this event is called when a new row is clicked. How else can I insert the newly created row in the database?
The code is not updating anything to the database as there is no code to update it.
You need to execute a query to update those new values. You could try using Commands:
http://msdn.microsoft.com/en-us/library/aa984369(v=vs.71).aspx
Or change the list to a DataTable, which allows you to update the values 'automatically' (a bit harder): http://msdn.microsoft.com/en-us/library/z1z2bkx2(v=vs.110).aspx
I would stay away form databinding, but if you can't, you can try this:
// Create a new row
DataRow dr = YourDataSet.Vendors.NewRow(); // Change 'Vendors' with your database table's name
// Add some data to your new row
dr[0] = 124;
// Insert the previous row
YourDataSet.Vendors.Rows.InsertAt(dr, 1); // Change the 1 to your index where you want to insert the data.

How to get value of ValueMember of datagridviewcomboboxcolumn

Friends, I'm using datagridviewcomboboxcolumn as column index 1 in my datagridview. I've fetched data from access database table and populated the datagridviewcomboboxcolumn by following manner:
for (int i = 0; reader.Read(); i++)
{
cmbBusCode.Items.Add(reader["BUSINESS_CODE"] + "-" + reader["BUSINESS_DESCRIPTION"]);
cmbBusCode.ValueMember = "BUSINESS_CODE";
}
Then I'm writing this:
cmbBusCode.DisplayIndex = 1;
cmbBusCode.Width = 200;
cmbBusCode.Name = "Code";
cmbBusCode.HeaderText = "Code";
And adding this column as
dgView.Columns.Add(cmbBusCode);
Combobox is being populated and I can select any one from the list. Now when I'm saving data I want to get the ValueMember of the selected item. To get this value I'm using following code but It's giving the string representation of the field "BUSINESS_CODE" not the value..Please help me so that get ValueMemeber of the selected item..
foreach (DataGridViewRow row in dgView.Rows)
{
string cd = row.Cells["Code"].Value.ToString();
}
The "item" you are adding to the column doesn't have a "BUSINESS_CODE" column (essentially, the item as you add it is simply a string), so that doesn't work.
What you need to do is assign items that contain multiple columns. One must be the BUSINESS_CODE column (as it is this column you want to be the value for the underlying field in the DataGridView), the other should be a display column that contains the concatenated value you're adding at the moment (DisplayMember and ValueMember).
Easiest would be to create a typed data set, add a table that contains the two columns I described and fill the table with the data from the data reader.
Then, add the table as the data source for the column.
You can try adding a DataGridViewComboBoxCell instead of a string to the cmbBusCode.Items collection. You can then specify Value in the cell. I'm not sure if this will work, but it's worth a try.

How can I use an unbound field in a DataGridView?

I'm working with a DataGridView having two TextBoxColumns and a DataGridViewButtonColumn.
As datasource I bound a DataTable with three columns: "ID", "Name", "Surname", but I need to show only the last two columns, so in my datagrid I defined only Name and Surname (and the button column) setting the AutoGenerateColumns property equal to false.
Now I need to use the "ID" field when the button on a row is clicked...
What's the correct way to get the "ID" value from the current row?
If it's about showing the other columns, I'd leave the ID column in, and hide it by setting Columns["ID"].Visible to false. Then you can just access the data in the column, but it doesn't show on screen.
To hide something .Visible do not works fast. Try to use DataView and BindingSource.
See this link.
There are filters that works very good.
Like this:
BindingSource tSource = new BindingSource();
DataView view = new DataView(_table);
tSource.DataSource = view;
Here I find a row:
DataRow row = CurrentRow(_dataGridView);
Here is the Implementation:
public static DataRow CurrentRow(DataGridView aGrid)
{
CurrencyManager xCM =
(CurrencyManager)aGrid.BindingContext[aGrid.DataSource, aGrid.DataMember];
DataRowView xDRV = (DataRowView)xCM.Current;
return xDRV.Row;
}
Something like this should work.
Hope this help you!
gridview.Rows[gridview.CurrentRow.Index].Cells["id"].Value
you will get "id" value of the current row

C# Best way to delete a row from typed dataset bounded by binding source

C# 2008 SP1.
I am deleting a row from a row that is currently selected on a datagridview.
I am using a Typed dataset and my datagridview is bounded to a binding source.
However, I think my technique is not the best, even though it works.
Many thanks for any advice,
DataRow[] drDelete;
// Get the value of the PK from the currently selected row
DataRowView drv = (DataRowView)bsAddressBook.Current;
int index = Convert.ToInt16(drv[0]);
// Find the actual data row from the primary key and delete the row
drDelete = dsCATDialer.AddressBook.Select(string.Format("ID = '{0}'", index));
dsCATDialer.AddressBook.Rows.Remove(drDelete[0]);
You could also delete directly using the BindingSource :
bsAddressBook.RemoveCurrent();
I think you can shorten this using the Row property of the DataRowView.
// Get the value of the PK from the currently selected row
DataRowView drv = (DataRowView)bsAddressBook.Current;
DataRow drDelete = drv.Row;
dsCATDialer.AddressBook.Rows.Remove(drDelete);

Categories