I am trying to put a filter on datagridview with ADGV (https://www.nuget.org/packages/ADGV/). However, when I create Datetime value columns by manually the filter does not display filtering by the Year, Month, and Day values.
When the column is created automatically, in runtime this columns shows exactly how to filter.
I want to create these DateTime value columns by manually. What should I do?
private void btnchonLop_Click(object sender, EventArgs e)
{
string TenLop = "Null"; string MaCLB = "Null"; int LichHoc = 3;
adgvHocSinhDuDK.AutoGenerateColumns = false;
adgvHocSinhDuDK.AutoGenerateContextFilters = true;
if (adgvDanhSachLop.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in adgvDanhSachLop.SelectedRows)
{
TenLop = row.Cells[2].Value.ToString();
MaCLB = row.Cells[7].Value.ToString();
LichHoc = (int)row.Cells[5].Value;
}
DataTable dt = HocSinhServices.LayHocSinhTheoLopDangKy(TenLop, MaCLB, LichHoc);
bdHocSinhDuDieuKien.DataSource = dt; //
adgvHocSinhDuDK.EnableFilter(clNgayNhapHoc); // Enabled Fitleter on NgayNhapHocColumn
}
else return;
}
By manually column
By Auto column
I had the same problem and I've got an answer for you: You have to set up the column ValueType BEFORE adding it to your AdvancedDataGridView.
Somewhere in your designer.cs, you have the declaration of columns and adgv, then you set the parameters of the adgv and then the parameters of the columns (default design in Visual Studio).
In the code, follow this:
First set the parameters of your column and add the ValueType:
example :
this.ContactDate.ValueType = typeof(System.DateTime);
Then add the column in your adgv
All because the filter of DateTime is activated on event "OnColumnAdd": if the ValueType is not DateTime, you won't get the right filter.
Related
In a C# WinForms project, I'm iterating through a DataGridView's DataSource as a DataTable and I'm doing a check on the source database and determining if a value in one of the columns is valid. If it is a valid value I want to hide it so I only end up with the DGV showing rows with invalid values.
Here's psuedo-code of what I have so far.
private void btnValidate_Click(object sender, EventArgs e)
{
DataTable dt = ((DataTable)dgvMyDataGridView.DataSource);
int intRowIndex;
for (intRowIndex = 0; intRowIndex <= dt.Rows.Count - 1; intRowIndex++)
{
DataRow drValidationRow = dt.Rows[intRowIndex];
string strNewValue = drValidationRow[5].ToString();
// Get the current row's db record ID as a string for the db query
int intCurrDgvRowId = int.Parse(dgvMyDataGridView[0, intRowIndex].Value.ToString());
// Determine if we need to show or hide the DGV's row
bool bNewValueIsValid = <db check for valid strNewValue>
if (bNewValueIsValid)
{
/*
* Hide the DGV row corresponding to the DT row ID
*/
}
}
}
I tried what seems most logical to me:
dgvmyDataGridView.Rows[intRowIndex].Visible = false;
But when I run that I get this error:
System.InvalidOperationException: 'Row associated with the currency manager's position cannot be made invisible.'
I can't just do something like drValidationRow.Visible = false, as there's no Visible property on that, I'm guessing because the row is from the DataTable not the DGV.
How do I accomplish this?
you dont need a counter. You can just refresh dgv if Rows.Count = 0 ?
I have used a database to populate Data-grids on many occasions.
However, in this instance, i can't seem to get the desired result.
I am trying to display only the people who have a birthday on the day.
i already have the dates, and the Birthday, but i can't seem to get teh rows to add to the datagridview.
here is how far i have got. But he "BirthdayGrdVw.DataSource" i can't seem to figure out.
i have been googling for 2 days.
I am new to this, and would really appreciate some assistance.
private void Tasks_VisibleChanged(object sender, EventArgs e)
{
Clients = Controller.DBQueries.GetPolicyList();
if(Clients != null)
{
foreach(DataRow row in Clients.Rows)
{
string ClientID = Clients.Rows[0]["ClientID"].ToString();
DateTime Birthdate = Controller.GetBirthdate(ClientID);
DateTime now = DateTime.Now;
if (Birthdate.Day == now.Day && Birthdate.Month == now.Month)
{
}
}
}
}
There appears to be things left out you your code, but without all of the information here is what I suggest you try if you are sure that your datatable has been populated.
Add a bindingsource object to your Windows Form by dragging it from the toolbox onto the form.
Set the it will be called bindingsource1. Set it's DataSource to the datatable like this:
BindingSource1.DataSource = "your data table name here";
And then set the DataGridView's DataSource to bindingsource1.
"Your DataGridView".DataSource = BindingSource1;
Or if you don't need some of the extra functionality that a BindingSource provides like "Filter" etc... You could bind the datatable directly to the DataGridView like:
DataGridView.DataSource = "your data table name here";
If Clients is a DataTable and you know what filtering you want to apply then why not use Filter on datatable as :
DataView dv = new DataView(Clients);
dv.RowFilter = "month(of your Birthday Col)="+now.Month+" and day(of your BirthDay Col)="+now.Day;
yourGridView.DataSource = dv.ToTable();
yourGridView.DataBind();
instead of all Foreach loop and all?
I have one datagrid and I want to show three column using it.
I have used stored procedure to show some records into datagrid.
stored procedure is :
procedure [dbo].[allKeys]
AS
select id,key,username from keys_TB
the key in this procedure is encrypted so, need to convert it i have done that conversion and have keep those key is ArrayList.
But problem is have bind the remaining id,username columns to datagrid, unable to bind ArrayList to datagrid.
Code behind :
DataSet ds = clsBusinessLogic.allKeys();
dgrv_allkey.DataSource = ds.Tables[0];
dgrv_allkey.AutoGenerateColumns = false;
dgrv_allkey.Columns["id"].DataPropertyName = "id";
DataGridViewColumn id = dgrv_allkey.Columns[0];
this.dgrv_allkey.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
id.Width = 60;
dgrv_allkey.Columns["username"].DataPropertyName = "username";
DataGridViewColumn Custname = dgrv_allkey.Columns[2];
Custname.Width = 199;
this.dgrv_allkey.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
this is how i have bind id and username to datagrid but don't have any clue about key.
and i have called the stored procedure [allKeys] through clsBusinessLogic.allKeys() method
First add an databinding complete event to the grid:
dgrv_allkey.DataBindingComplete += dgrv_allkey_DataBindingComplete;
Then add the result set of stored procedure as the grid datasoruce:
dgrv_allkey.DataSource = ds.Tables[0];
dgrv_allkey.Columns["id"].DataPropertyName = "id";
////and other formating what ever needed.
Due to setting the datasource the event will be fired, and then in this event change the value of the key cell for each row.
private void dgrv_allkey_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
// Change Column Value for the DataGridView.
foreach (DataGridViewColumn i in dataGridView1.Columns)
{
if (i.Name == "key")
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string oldvalue = row.Cells["key"].Value as string;
if (!string.IsNullOrEmpty(oldvalue))
{
// perform decoding here and set the decoded value here..
}
}
}
}
}
I'm currently working on an "advanced" search form for my application. I'm using a datagridview to display the results. The idea is to be able to search thoroughly (with lots of options).
Currently I fill the datagridview like this:
dgvData.AutoGenerateColumns = false;
if (cbbKlant.SelectedItem != null)
{
dgvData.DataSource = StatistiekManagement.getOpdrachten((klant)cbbKlant.SelectedItem);
//ID kolom
DataGridViewTextBoxColumn id = new DataGridViewTextBoxColumn();
id.Name = "ID";
id.DataPropertyName = "opdracht_id";
//Plaatsen kolom
DataGridViewTextBoxColumn plaatsen = new DataGridViewTextBoxColumn();
plaatsen.Name = "Plaatsen";
plaatsen.DataPropertyName = "aantal_personen";
//Vertrekplaats kolom
DataGridViewTextBoxColumn vertrek = new DataGridViewTextBoxColumn();
vertrek.Name = "Vertrek";
vertrek.DataPropertyName = "locatie_id";
this.dgvData.Columns.Add(id);
this.dgvData.Columns.Add(plaatsen);
this.dgvData.Columns.Add(vertrek);
}
My problem here is I want to add information to the datagridview from another table. For example: I have a contract and this contract has a location. How do I display the location into this datagridview?
I also use LINQ TO SQL to get my data from the database.
Thanks,
Thomas
You can't bind a datagridview to two different sources.
The solution for you would be to write a SQL statement to join two different tables and then populate a dataset with that. You could then use that as your data source.
There are several ways to attach the location. The easiest would be if you could add the Location as a property to the bound baseclass. It doesn't have to be a field in the database, just a property you could bind to. If inheriting isn't an option, sometimes encapsulation can work.
Besides the above, you can always add a non-bound column to your (bound) datagridview. The value which it should display, could come from any source you like. One of the ways to display the value is to use the datagridview's cellformatting event:
//inside initialization void
dgvData.CellFormatting+=new DataGridViewCellFormattingEventHandler(dgvData_CellFormatting);
dvcol = new DataGridViewTextBoxColumn();
dgvData.Columns.Add(dvcol);
}
DataGridViewColumn dvcol;
void dgvData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dvcol != null && e.RowIndex != -1 && e.ColumnIndex == dvcol.Index)//where Column1 is your combobox column
{
var rec = (YourRecordTypeSuchAsContract)dgvData.Rows[e.RowIndex].DataBoundItem;
e.Value = ""; //get description based on the rec
}
}
I'm trying to filter a deadline column in a datagridview by 2 datetimepickers - startDate and endDate.
datagridview is TaskTable2,
datetimepicker1 is startSchedule,
datetimepicker2 is endSchedule and
deadline in datagridview is deadlineRow
So far I have got the following code which is successfully making the rows invisible which are not between the selected start and end date.
private void scheduleButton_Click(object sender, EventArgs e)
{
DateTime startSchedule = startDate.Value.Date;
DateTime endSchedule = endDate.Value.Date;
if (startSchedule <= endSchedule)// runs foreach loop if startdate and enddate are valid
{
foreach (DataGridViewRow dr in TaskTable2.Rows)// loops through rows of datagridview
{
string deadline = dr.Cells["Deadline"].Value.ToString(); // gets deadline values
DateTime deadlineRow = Convert.ToDateTime(deadline); // converts deadline string to datetime and stores in deadlineRow variable
if (startSchedule <= deadlineRow && deadlineRow <= endSchedule) // filters deadlines that are => startDate and <= endDate
{
dr.Visible = true; // display filtered rows here.
}
else
{
dr.Visible = false; // hide rows that are not beteen start and end date.
}
}
}
else
{
MessageBox.Show("Please ensure Start Date is set before End Date."); // ensures user selects an end date after the start date.
}
}
However, I have a few existing problems:
The application crashes and I get the following error when I select a date range that will display no tasks:
'Row associated with the currency manager's position cannot be made invisible'
I have a print button that is supposed to print the filtered results.
However, it is printing all data stored in the datagridview, even if some rows are visible=false from pressing the schedule button so I'm guessing I need to use a different approach to remove the rows rather than hide them.
The datagridview is bound to an XML file so data can be removed from the datagridview for filtering and printing aslong as they remain in the XML file.
Any help would be greatly appreciated!
Thankyou
I would use the Filter property on the bindingsource for the datagridview. The Filter property allows you to view a subset of the DataSource.
Example from MSDN:
private void PopulateDataViewAndFilter()
{
DataSet set1 = new DataSet();
// Some xml data to populate the DataSet with.
string musicXml =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<music>" +
"<recording><artist>Coldplay</artist><cd>X&Y</cd></recording>" +
"<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" +
"<recording><artist>Dave Matthews</artist><cd>Live at Red Rocks</cd></recording>" +
"<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" +
"<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" +
"</music>";
// Read the xml.
StringReader reader = new StringReader(musicXml);
set1.ReadXml(reader);
// Get a DataView of the table contained in the dataset.
DataTableCollection tables = set1.Tables;
DataView view1 = new DataView(tables[0]);
// Create a DataGridView control and add it to the form.
DataGridView datagridview1 = new DataGridView();
datagridview1.AutoGenerateColumns = true;
this.Controls.Add(datagridview1);
// Create a BindingSource and set its DataSource property to
// the DataView.
BindingSource source1 = new BindingSource();
source1.DataSource = view1;
// Set the data source for the DataGridView.
datagridview1.DataSource = source1;
//The Filter string can include Boolean expressions.
source1.Filter = "artist = 'Dave Matthews' OR cd = 'Tigerlily'";
}
I use this type of Filter to show data based on account. For an account, I have a textbox when the user places the account number and I use the TextChanged Event to apply the filter. Then I have a button that is used to remove the Filter from the binding source.
If you want to filter by date you can following instructions in this SO question:
BindingSource Filter by date
Using the filter on a date that is not present should not crash the app, it will just display nothing.
Found a solution to the exception here:
http://discuss.itacumens.com/index.php?topic=16375.0
I added this to my code directly before I attempt to set the row to be not visible. row is my ForEach loop variable. I check to see if its selected and if it is attempt to clear the row and cell selection before setting the visible property.
If gridItems.SelectedRows.Count > 0 AndAlso row.Index = gridItems.SelectedRows(0).Index Then
'fixes dumb exception with row.visible = false
gridItems.ClearSelection()
gridItems.CurrentCell = Nothing
End If
It seems the issue is with making the current row or cell not visible.
I faced exact same problem with exception 'Row associated with the currency manager's position cannot be made invisible'.
dgridView.CurrentCell = null;
dgridView.Rows[i].Visible = false;
Just setting the CurrentCell to null fixed it for me. I haven't checked it further, if it breaks something.