Disable date chosing in DateTimePicker winform [duplicate] - winforms

How to restrict DateTimePicker to select the time only? I don't know how to disable calendar control which drops when you press the button at the right of DateTimePicker.

A snippet out of the MSDN:
'The following code sample shows how
to create a DateTimePicker that
enables users to choose a time only.'
timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Time;
timePicker.ShowUpDown = true;
And for anyone who wants to know what it looks like:

...or alternatively if you only want to show a portion of the time value use "Custom":
timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Custom;
timePicker.CustomFormat = "HH:mm"; // Only use hours and minutes
timePicker.ShowUpDown = true;

You want to set its 'Format' property to be time and add a spin button control to it:
yourDateTimeControl.Format = DateTimePickerFormat.Time;
yourDateTimeControl.ShowUpDown = true;

If you want to do it from properties, you can do this by setting the Format property of DateTimePicker to DateTimePickerFormat.Time and ShowUpDown property to true. Also, customFormat can be set in properties.

The best way to do this is this:
datetimepicker.Format = DatetimePickerFormat.Custom;
datetimepicker.CustomFormat = "HH:mm tt";
datetimepicker.ShowUpDowm = true;

Add below event to DateTimePicker
Private Sub DateTimePicker1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles DateTimePicker1.KeyPress
e.Handled = True
End Sub

Related

Get selected text from combobox in winium

How can I get the selected option from a combo box using winium?
I used Select class from selenium. But it is throwing error like
"org.openqa.selenium.UnsupportedCommandException: 'getElementTagName'
is not valid or implemented command".
I used the following code:
Select select = new Select(driver.findElement(By.id("cmbLocation")));
String option = select.getFirstSelectedOption().getText();
Try this.
WebElement combo = winDriver.findElementById(autoID);
String option = combo.getAttribute("NameProperty");
The NameProperty changes with the value of selected option.

How can Add items to Binded Datasource Combo Box?

Hi I am new to C#. I have tried following way to add new item to my bound ComboBox but it won't give any result.
Is it possible to add new item to bound ComboBox (Here Problem is ID is Bigint data type but I want to add Select ID)?
If it is possible, please provide piece of code
try
{
objSqlExecute.OpenConnection();
string strQuery = objQueryManager.GetEmployeeRecords();
//Add Extra Items to combo Box
cmbEmployeeID.Items.Add("Select Id");
DataTable dtEmployee = objSqlExecute.GetRecordExecution(strQuery);
// DataRow dtNew = dtEmployee.NewRow();
// dtNew["ID"] = "Select ID";
// dtNew["FName"] = "";
//dtEmployee.Rows.InsertAt(dtNew, 0);
cmbEmployeeID.DataSource = dtEmployee;
cmbEmployeeID.DisplayMember = "ID";
cmbEmployeeID.ValueMember = "FName";
}
try
{
objSqlExecute.OpenConnection();
string strQuery = objQueryManager.GetEmployeeRecords();
//Add Extra Items to combo Box
DataTable dtEmployee = objSqlExecute.GetRecordExecution(strQuery);
cmbEmployeeID.DataSource = dtEmployee;
cmbEmployeeID.DisplayMember = "ID";
cmbEmployeeID.ValueMember = "FName";
cmbEmployeeID.Items.Insert(0, "None Selected");
}
Did you try your query to make sure it returns values? returning multiple records, single or none?
Do you want to add ONE new item at random intervals?
Or else do you have an option to INSERT all items at once?
Can you try adding toString() for converting BigInt?
Notes:
The arcticle here gives an insight to add a new item to a combobox using sql.
Looking at the questions you are posting, to see a sample of how to use ListItems in this scenario, you could refer to the web link.

Is there a way to force a DataGridView to fire its CellFormatting event for all cells?

We use the CellFormatting event to colour code cells in various grids all over our application.
We've got some generic code which handles export to Excel (and print) but it does it in Black & White. Now we want to change this and pick up the colour from the grids.
This question & answer has helped (and it works) ... except there's a problem with larger grids that extend beyond a single screen. The portions of the grid which haven't yet been displayed on screen are (logically) never getting their CellFormatting code fired, and so their underlying colour never gets set. As a result, in Excel, the colour coding fizzles out half way down the page.
Seems there are three solutions:
1) Tell the user he has to scroll to all parts of the grid before doing an Export to Excel. Ha! Not a serious solution
2) Programmatically scroll to all parts of the grid before doing an Export to Excel. Only slighly less horrible than (1)
3) In our Export to Excel code, fire something at the top which tells the DataGridView to paint/format its entire area e.g.
MyDataGridView.FormatAllCells()
Is there something that does something like this???
Oh, and there is a fourth option but this will involve touching a massive amount of existing code:
4) Stop using CellFormatting event, format the cells at load time. Problem with this is we'd have to retool every grid in our application since CellFormatting is the way we've done it since year dot.
As noted in the other answers, accessing the DataGridViewCell.FormattedValue is indeed an easy way to force the CellFormatting event to be (re-)called for a specific cell. In my case, however, this property was also leading to undesirable side-effects involving the auto-resizing of the columns. While searching a long time for a workable solution, I finally encountered the following magic methods that work perfectly: DataGridView.Invalidate(), DataGridView.InvalidateColumn(), DataGridView.InvalidateRow(), and DataGridView.InvalidateCell().
These 4 methods force the CellFormatting event to be re-called only for the specified scope (cell, column, row, or whole table), and also without causing any nasty auto-resizing artifacts.
I have a possible solution - In your export function access the Cell.FormattedValue property of each cell. According to Microsoft, this forces the CellFormatting event to fire.
Assuming, as #DavidHall suggests, there is no magic .FormatAllCells our only option is to stop using CellFormatting.
However, new problem here is that applying cell style formatting during load doesn’t seem to have any effect. Lots of posts out there if you Google it. Also they point out that if you put the same code under a button on the form and click it after loading (instead of in the load, the code will work ... so the grid has to be visible before styling can apply). Most advice on the topic suggests you use ... drumroll ... CellFormatting. Aargh!
Eventually found a post which suggests using the DataBindingComplete event of the grid. And this works.
Admittedly, this solution is a variant of my unwanted option "4".
I had the same problem and I've ended up with something quite similar to your solution #4.
like you, I've used the DataBindingComplete event. but, Since I've used Extension method, the changes in the existing code are bearable:
internal static class DataGridViewExtention
{
public static void SetGridBackColorMyStyle(this DataGridView p_dgvToManipulate)
{
p_dgvToManipulate.RowPrePaint += p_dgvToManipulate_RowPrePaint;
p_dgvToManipulate.DataBindingComplete += p_dgvToManipulate_DataBindingComplete;
}
// for the first part - Coloring the whole grid I used the `DataGridView.DataBindingComplete` event:
private static void p_dgvToManipulate_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow objCurrRow in ((DataGridView)sender).Rows)
{
// Get the domain object from row
DomainObject objSelectedItem = (DomainObject)objCurrRow.DataBoundItem;
// if item is valid ....
if objSelectedItem != null)
{
// Change backcolor of row using my method
objCurrRow.DefaultCellStyle.BackColor = GetColorForMyRow(objSelectedItem);
}
}
}
// for the second part (disabling the Selected row from effecting the BackColor i've setted myself, i've used `DataGridView.RowPrePaint` event:
private static void p_dgvToManipulate_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
// If current row about to be painted is selected by user
if (((DataGridView)sender).Rows[e.RowIndex].Selected)
{
// Get current grid row
var objGridRow = ((DataGridView)sender).Rows[e.RowIndex];
// Get selectedItem
DomainObject objSelectedItem = (DomainObject)objGridRow.DataBoundItem;
// if item is valid ....
if (objSelectedItem != null && objSelectedItem.ObjectId != 0)
{
// Set color for row instead of "DefaultCellStyle" (same color as we used at DataBindingComplete event)
objGridRow.DefaultCellStyle.SelectionBackColor = GetColorForMyRow(objSelectedItem);
}
// Since the selected row is no longer unique, we need to let the used to identify it by making the font Bold
objGridRow.DefaultCellStyle.Font = new Font(((DataGridView)sender).Font.FontFamily, ((DataGridView)sender).Font.Size, FontStyle.Bold);
}
// If current row is not selected by user
else
{
// Make sure the Font is not Bold. (for not misleading the user about selected row...)
((DataGridView)sender).Rows[e.RowIndex].DefaultCellStyle.Font = new Font(((DataGridView)sender).Font.FontFamily,
((DataGridView)sender).Font.Size, FontStyle.Regular);
}
}
}
A possible solution if you do want to reuse the formatting provided during the Cellformatting-event (e.g. the cellstyle-elements like fontbold and backgroundcolor). These cellstyles seem to be only available between the 'cellformatting' and 'cellpainting' events but not in the datagridview-cell's style itself..
Capture the cellstyles during the cellformatting-event with a second handler like this:
in the exportmodule add a shared list, array or dictionary to store the cellstyles:
Dim oDataGridFormattingDictionary as Dictionary(Of String, DataGridViewCellStyle) = nothing
initialize the dictionary and add a second handler to the datagridview in your printing or export-code. In vb.net something like this:
oDataGridFormattingDictionary = New Dictionary(Of String, DataGridViewCellStyle)
AddHandler MyDatagridviewControl.CellFormatting, AddressOf OnPrintDataGridView_CellFormatting
Add the code for the handler
Private Sub OnPrintDataGridView_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs)
If e.RowIndex > -1 AndAlso e.ColumnIndex > -1 AndAlso Not e.CellStyle Is Nothing Then
If Not oDataGridFormattingDictionary Is Nothing andalso oDataGridFormattingDictionary.ContainsKey(e.RowIndex & "_" & e.ColumnIndex) = False Then
oDataGridFormattingDictionary.Add(e.RowIndex & "_" & e.ColumnIndex, e.CellStyle)
End If
End If
End Sub
Very important: to make sure the original cellformating-event (AND the second cellformatting-handler after that) are actually called you have to request the formattedvalue for each cell that you want to print (e.g.
oValue = Datagridview.rows(printRowIndex).Cells(printColumnIndex).FormattedValue)
!
When printing you can now check if the cell has formatting. E.g.:
if not oDataGridFormattingDictionary is nothing andalso oDataGridFormattingDictionary.ContainsKey(printRowIndex & "_" & printColumnIndex) Then
... the cellstyle is accesible via:
oDataGridFormattingDictionary(printRowIndex & "_" & printColumnIndex)
end if
at the end of the export or printcode remove the handler and set the dictionary to nothing
RemoveHandler DirectCast(itemToPrint.TheControl, DataGridView).CellFormatting, AddressOf OnPrintDataGridView_CellFormatting
oDataGridFormattingDictionary = nothing

IEditableObject in MVVM

Can you think of a scenario where IEditableObject would be still usefull in an MVVM-based WPF application? If so, do you have an example that demonstrates this.
I have used IEditableObject in one of my applications. For example if you have a dialog for editing something, you could implement IEditableObject on your ViewModel. You call BeginEdit() when the dialog opens, EndEdit() when the user clicks OK, and CancelEdit() when the user clicks cancel.
IEditableObject is a good interface anytime you want to be able to roll back changes.
I've got an implementation of IEditableObject in my application so that I can keep from updating my data model if what the user has entered is invalid, and roll back to the original values if the user abandons changes.
Within a type being displayed in a DataGrid. This was needed since when I am making use of tabs and a DataGrid is being stored within that tab switching the tabs needed to force a commit so to speak within the DataGrid if a cell was active; rolling back the changes since they were not committed. T
There is a behavior being applied to the DataGrid to achieve this functionality but the IEditableObject portion is below.
private IDatabaseConnection _copy;
void IEditableObject.BeginEdit()
{
if (this._copy == null)
this._copy = _container.Resolve<IDatabaseConnection>();
_copy.Database = this.Database;
_copy.DisplayName = this.DisplayName;
_copy.HostName = this.HostName;
_copy.Username = this.Username;
_copy.Password = this.Password;
}
void IEditableObject.CancelEdit()
{
this.Database = _copy.Database;
this.DisplayName = _copy.DisplayName;
this.HostName = _copy.HostName;
this.Username = _copy.Username;
this.Password = _copy.Password;
}
void IEditableObject.EndEdit()
{
_copy.Database = String.Empty;
_copy.DisplayName = String.Empty;
_copy.HostName = String.Empty;
_copy.Username = String.Empty;
_copy.Password = String.Empty;
}

SubSonic and a dateTimePicker control on a Windows Form

Question #1: Latest working Version
I'm currently using SubSonic 2.1 built 491.
Is there a later build? Where can I get it?
I know 2.2 was released but it doesn't come with a Setup and I wouldn't know how to modify the App.Config/Web.Config to work with it.
Question #2: Issue with dateTimePicker control on Windows Form.
I keep getting System.FormatException trying to retrieve data From SubSonic to that control or saving data from that control to the Database through SubSonic.
For example, if I want to save the Time only, I can use the .Text property. To save the Date, I need to use the .Value property of the control.
I've tried all sorts of conversion such as Convert.ToDateTime(dateTimePicker.Value.ToString()) and others but I can't find a consistent pattern that would not throw an exception. Any help on this would be greatly appreciated.
Re Question 1 - I don't think any app.config / web.config change is required between SS2.1 and 2.2
For Question 2 - are you using the new data types in MSSQL2008 by any chance? If so, SS2.2 doesn't seem to handle them properly yet.
Just stumbled upon your post.
I'm not sure if It was a FormatException, but I got a Exception with a databound DateTimePicker, too.
The problem is that
DateTimePicker.MinimumDateTime = #1/1/1753#
while
DateTime.MinValue = #1/1/0001#
New DateTime = #1/1#0001#
So if bind a property to a DataGridView that returns a DateTime value earlier than #1/1/1753# or later then #12/31/9998# ( DateTimePicker.MaximumDateTime ) you get an exception.
I solved this with my own inherited DateTimePicker (sorry, but it's written in vb)
To use it you can just bind your Subsonic object to the value property. But you have to set the ShowCheckBox property to true and bind a bool value to the CheckedValue property (to indicate that the date is set) which is persisted in your db, too.
Now If an empty date is returned, the date is set to Now and the checkedValue to false, leading to a disabled DateTimePicker.
If you check the Checkbox or choose a date with the calender) the checkbox is set to true and the Checkbox is checked.
Attention: Do not bind the Checked property directly, bind the CheckedValue property.
Imports System.ComponentModel
Public Class MyDateTimePicker
Inherits System.Windows.Forms.DateTimePicker
<Bindable(True)> _
Public Overloads Property Value() As DateTime
Get
If Not MyBase.Checked And (MyBase.Value < DateTimePicker.MinimumDateTime Or MyBase.Value > DateTimePicker.MaximumDateTime) Then
Return DateTime.Now
Else
Return MyBase.Value
End If
End Get
Set(ByVal value As DateTime)
If ((value < DateTimePicker.MinimumDateTime Or value > DateTimePicker.MaximumDateTime) Or value = #1/1/1900#) Then
MyBase.Value = DateTime.Now
MyBase.Checked = False
Else
MyBase.Value = value
End If
End Set
End Property
Private _CheckedValue As Boolean
<Bindable(True)> _
Public Property CheckedValue() As Boolean
Get
Return _CheckedValue
End Get
Set(ByVal value As Boolean)
_CheckedValue = value
End Set
End Property
Protected Overrides Sub OnMouseUp(ByVal e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseUp(e)
RefreshCheckedValue()
End Sub
Protected Overrides Sub OnKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs)
MyBase.OnKeyDown(e)
RefreshCheckedValue()
End Sub
Private Sub RefreshCheckedValue()
CheckedValue = Me.Checked
If Not Me.DataBindings("CheckedValue") Is Nothing Then
Me.DataBindings("CheckedValue").WriteValue()
End If
End Sub
Protected Overrides Sub OnBindingContextChanged(ByVal e As System.EventArgs)
MyBase.OnBindingContextChanged(e)
Static checkedInitialized As Boolean
If Not checkedInitialized AndAlso Not Me.DataBindings("CheckedValue") Is Nothing Then
Me.Checked = Me.CheckedValue
checkedInitialized = True
End If
End Sub
End Class

Resources