i am adding an unbound checkbox to my gridcontrol to make multi checking to the rows like the Foto.
now i need to retrive these selected rows data in the code.
any help for code helping me get the selected rows data.
It appears you're using the GridControl's built-in checkbox selection system. In that case, you can use the GridView's GetSelectedRows method to retrieve an array of selected row handles.
int[] selectedRowHandles = gridView1.GetSelectedRows();
for (int i = 0; i < selectedRowHandles.Length; i++)
{
object row = gridView1.GetRow(i); //get a row, do something with it
}
Related
So for example,
I have this datagridview which is bounded to a datatable:
A
B
C
1
4
7
2
5
8
3
6
9
And B is the column I want to check the value for, for example I have a saved int value of 5. The code should check if in B column there is a value of 5, if true the all the rows with value 5 visibility is set to true, and all other rows will have their visibility set to false.
Fow now, I have tried this little code (though it checks the all cells but not by specific column):
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
int rowIndex = row.Index;
if (row.Cells[i].Value.ToString().Equals("16"))
{
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[dataGridView1.DataSource];
currencyManager1.SuspendBinding();
dataGridView1.Rows[rowIndex].Visible = true;
currencyManager1.ResumeBinding();
}
else
{
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[dataGridView1.DataSource];
currencyManager1.SuspendBinding();
dataGridView1.Rows[rowIndex].Visible = false;
currencyManager1.ResumeBinding();
}
}
}
Now about this CurrencyManager, when I tried to hide the rows without it, it simply error'd me, but now with it all rows visibility set to false. And the problem is I don't understand where to look at and how to fix it, even if the code checks the cells the value "16" in code should show some rows in datagridview but it doesn't.
It's a lot simpler. For a datagridview bound like this:
myDgv.DataSource = dt;
We can dynamically filter the dgv like this:
dt.DefaultView.RowFilter = "[B] = 5"; //only show rows where B is 5
When a DGV's DataSource is set to a datatable it binds to the DataView exported by the DefaultView property so that you can change properties of the view like filter and sort, and it will influence the DGV. You also have the option of creating your own DataView based on the table and binding the DGV to that. For more info on the syntax you can use in a RowFilter, look at DataColumn.Expression
When working with bound data, do try to get into the habit of accessing the data by looking in the container (the datatable) rather than enumerating the DGV and pulling values out of it
You might find it more useful to bind your datatable to a BindingSource and then bind the BindingSource to the DGV- a bindingsource also has a Filter property with the same syntax but also maintains the notion of current row/ as the user changes the current row in the DGV the value of the Current property on the bindingsource changes, making it easier to manipulate the current row in code
You indicate that this is all set up in the forms Designer, which means on your form you have:
a datagridview called _xDataGridView
a binding source called _xBindingSource
a dataset called _xDataSet
the bindingsource's DataSource is set to the dataset and the datamember is set to the table name in the dataset, and the datagridview's DataSource is set to the bindingsource
(mostly I'm just describing the setup to make sure it's right)
All you need to do is:
_xBindingSource.Filter = "[B] = 5";
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
So I have found that one can get the bound datatable row for a datagridview row, however, I am seeking to do the opposite. I have the following working code that sorts the datatable rows into an array sorted by a date field. I am then performing some logic to fill a value based on how much quantity is available. When the quantity available is less than the quantity required, I want to color the datagrid row to let the user know of the situation. How can I refer to the correct datagridview row at this point?
Update For Clarity : This is a winform using a datagridview. The code shown is on a "Match All" button. Its purpose is to match a Qty to Transfer value from a Qty Required cell up to an available quantity for the row's Item.
Dictionary<string, float> availableQtys = new Dictionary<string, float>();
DataView view = new DataView(dtStaged);
DataTable distinctItems = view.ToTable(true, "Item");
for (int i = 0; i < distinctItems.Rows.Count; i++)
{
availableQtys[distinctItems.Rows[i].Field<string>(0)] =
Controller.Instance.GetAvailableQty(distinctItems.Rows[i].Field<string>(0), ddl_SourceLocation.SelectedValue.ToString());
}
DataRow[] rowList = dtStaged.Select("", "Req Ship ASC");
foreach (DataRow row in rowList)
{
if (ddl_SourceLocation.SelectedValue.ToString().Trim() == row["Dest Site"].ToString().Trim())
continue;
if (availableQtys[row["Item"].ToString()] < Convert.ToSingle(row["Qty Required"]))
{
row["Qty to Transfer"] = availableQtys[row["Item"].ToString()];
availableQtys[row["Item"].ToString()] = 0.0f;
warnUser = true;
// HERE I want to set the color of the matching data grid row
}
// some other stuff
}
As far as I understand, you use WinForms. And you probably use DataGridView to display your data.
The best solution for you is to create custom cell template.
For instance you can inherit DataGridViewTextBoxCell, and override OnPaint method.
There are 'rowIndex', and 'value' among the parameters of OnPaint method.
This way your template will be able to consider data bound item and paint the cell accordingly.
Another solution is to manually update rows color every time your data changed.
Here is an example.
I have a DataGridView bound to a database Table. Visual Studio created the grid and a binding navigator Toolstrip. Navigating, Insert, Delete are working fine...
BUT:
If I sort the grid by clicking on some column header, inserting a row is messing up the grid. The row index passed to the RowsAdded event handler is wrong. Its always the index of last row which was fine in unsorted mode before. In sorted mode I am editing the wrong row and see no chance to find out the index of the right one.
All data bound columns are displayed correctly even though index is always the last row. The problem occurs with not data bound columns. In my case an image column depending on a data bound column. The image is always drawn in the last row. Thus ignoring sorting...
Here is what I am doing in the RowsAdded event handler:
for (int i = 0; i < e.RowCount; ++i)
{
DataGridViewRow row = dataGridView_Energietraeger.Rows[i + e.RowIndex];
object idObj = row.Cells[Column_Id.Index].Value;
if (idObj is System.DBNull || idObj == null)
{
// set default values to all cells in new row...
// set icon indicating ro/ rw mode - wrong row when sorted!
row.ReadOnly = (bool)readonlyObj;
SetIconCellImage(row);
}
else
{
object readonlyObj = row.Cells[Column_Readonly.Index].Value;
if (!(readonlyObj is System.DBNull) && readonlyObj != null)
{
row.ReadOnly = (bool)readonlyObj;
SetIconCellImage(row); //
}
}
}
Any hints?
May be I did not understood logics of databinding and how to access rows and datasources. but I can't see my mistake yet. Thanks in advance...
Holger
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.