I have a Windows Form VS2010 .NET 4 project with a standard DataGridView bound to a datasource on a form.
The grid has a text column that I want to be a point and edit at the character clicked to.
Like normal textbox/editors when you click on the character you want to adjust. If possible I would also like to use the UP/DOWN keys to move between rows but would like the cursor to move to the same character position obviously in the same column without selecting the entire text.
I have tried a few things:
DataGridView1.ClearSelection()
DataGridView1.BeginEdit(False)
The BeginEdit just puts the cursor at the end of the text, which means another click to point to the character position for editing.
I know a Commercial grid like DevExpress defaults to editing in which you can click to the correct character position with one click but obviously costs money.
I have tried in the DataGridView1_EditingControlShowing event
If TypeOf e.Control Is System.Windows.Forms.DataGridViewTextBoxEditingControl Then
Dim tb As TextBox = e.Control
tb.SelectionStart = 5
tb.SelectionLength = 5
End If
But this does nothing.
I am just trying to remove the two or three clicks to get to the character position that needs adjustment.
I haven't looked at a Custom DataColumn as yet.
Any suggestions would be greatly appreciated.
There is no good out of the box way of doing this. The closest there is is to set the EditMode of the grid to EditOnEnter but that means you only need two clicks, not three.
You will need to write your own column type.
Someone has done just that here.
I haven't checked if that example handles up and down - if it doesn't then you were on the right track with the SelectionStart and SelectionLength properties, just grab the caret position of the cell you are leaving and apply it to the new cell.
It turns out that setting these properties is a little bit more involved that I remembered (possibly because I was already using a MaskedTextBox custom column type last time I did this).
The code below (in c# but the principle holds for vb.Net and I can give the vb code if you can't convert it yourself) works happily - could be tidied up by putting it into a custom control but I'll leave that as an exercise :)
First I add a handler for the EditingControlShowing event:
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridViewTextBoxEditingControl t = e.Control as DataGridViewTextBoxEditingControl;
current_control = t;
t.Leave += new EventHandler(t_Leave);
}
In the method above current_control is a form level private variable. The event handler for t looks like this:
void t_Leave(object sender, EventArgs e)
{
cell_caret_pos = current_control.SelectionStart;
}
There again we have a class level private field - cell_caret_pos.
Then what I found was that to set SelectionStart and SelectionLength you need to work within the CellEnter event handler:
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.BeginEdit(false);
DataGridViewTextBoxEditingControl editControl =
(DataGridViewTextBoxEditingControl)dataGridView1.EditingControl;
if (cell_caret_pos != 0)
{
editControl.SelectionStart = cell_caret_pos;
editControl.SelectionLength = 0;
}
}
Related
How can I toggle the checkbox of an item in a CheckedListbox if CheckOnClick is True, but SelectionMode is None..?
If I set SelectionMode to One it works as expected, but I would like to prevent items in the list from being selected. The only purpose of the CheckedListbox is to use the checkboxes; having items selected is not desired.
I tried a bit of code with the various Click and Mouse events, but none of them seem to report the item in the list that was clicked. If I could determine that, it would be a simple matter to toggle the checkbox of the clicked item.
The MouseClick event will tell you when the control was clicked and where. Determine whether the click was on an item and which one, then toggle it:
Private Sub CheckedListBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles CheckedListBox1.MouseClick
Dim clickedIndex = CheckedListBox1.IndexFromPoint(e.X, e.Y)
If clickedIndex <> ListBox.NoMatches Then
CheckedListBox1.SetItemChecked(clickedIndex, Not CheckedListBox1.GetItemChecked(clickedIndex))
End If
End Sub
After a little testing, I would say that you need to consider “how” you want to achieve the non-selection mode you describe. As you have noted, if you set the CheckedListBoxes SelectionMode to None… then basically the check boxes become unusable.
The user cannot check or un-check any check box, as you already know… and this is why you want “your” code to change the check boxes checked state. So, you have now inherited the job of changing the check boxes check state because you set its “SelectionMode” to “None" … ? …
In addition, when the selection mode is set to “None” … then many “typical” properties of the CheckedListBox will lose functionality and become useless. Example, the checked list boxes SelectedItem property will always be null and its SelectedIndex property will most likely always be -1. Meaning, most “selection” type events will need to find what item was clicked by using the mouse location as shown in another answer.
The main point here is that when you decided to set the checked list boxes selection mode to “None”, then you basically open the door for more coding/responsibility on your part as far as “managing” the checked list box. I am just saying that the out-of-the-box .Net CheckedListBox is not feature rich and is a basic control. I am guessing there “may” be a third-party CheckedListBox Control that may have this “non-selected” functionality built-in.
So… I suggest another approach… however… it also has some drawbacks… basically you have to create a new Class MyCheckedListBox type “Control” that inherits from the CheckedListBox and then override its draw method to paint the cell the way we want.
I tend to avoid creating new controls. However, this will allow us to “keep” the CheckedListBoxes “selection functionality” by keeping its SelectionMode set to One. In addition to removing the job of “your” code having to manage each check box’s check state… we can also use all the checked list boxes “selection” events and use them as we typically would using the list boxes “selection” properties.
Below is a crude example of how to override the CheckedListBox’s Draw method to keep the “selected” items back color to the same color of the non-selected items.
class CheckedListBox_NoSelect : CheckedListBox {
protected override void OnDrawItem(DrawItemEventArgs e) {
DrawItemEventArgs new_e_Args = new DrawItemEventArgs
(e.Graphics,
e.Font,
new Rectangle(e.Bounds.Location, e.Bounds.Size),
e.Index,
(e.State & DrawItemState.Focus) == DrawItemState.Focus ? DrawItemState.Focus : DrawItemState.None,
this.ForeColor,
this.BackColor);
base.OnDrawItem(new_e_Args);
}
}
The code above is a simplified version of this SO question… How change the color of SelectedItem in CheckedListBox in WindowsForms? …
As I started, you will have to decide which approach you need. I may tend to go the route of #user18387401‘s answer … simply to avoid creating a new User Control. However, if you want this functionality for all the CheckedListBoxes, then creating the control may be a better approach.
Below is a full example of what is described above.
The CheckedListBox on the left is a regular CheckedListBox and uses the approach from user18387401‘s answer. The CheckedListBox on the right is our new control class CheckedListBox_NoSelect above.
For each control, the SelectedIndexChanged event is wired up to demonstrate that the checked list box on the left with its SelectionMode set to None will always have its SelectedItem set to null and its SelectedIndex will always be set to -1. However, it is not difficult to figure out “which” item was selected using user18387401‘s approach. This index is also displayed in its SelectedIndexChanged event.
private void Form1_Load(object sender, EventArgs e) {
checkedListBox1.SelectionMode = SelectionMode.None;
checkedListBox1.Items.Add("Item 1");
checkedListBox1.Items.Add("Item 2");
checkedListBox1.Items.Add("Item 3");
checkedListBox1.Items.Add("Item 4");
checkedListBox1.Items.Add("Item 5");
checkedListBox1.CheckOnClick = true;
// Leave default selection mode to "One"
checkedListBox_NoSelect1.Items.Add("Item 1");
checkedListBox_NoSelect1.Items.Add("Item 2");
checkedListBox_NoSelect1.Items.Add("Item 3");
checkedListBox_NoSelect1.Items.Add("Item 4");
checkedListBox_NoSelect1.Items.Add("Item 5");
checkedListBox_NoSelect1.CheckOnClick = true;
}
private void checkedListBox1_MouseClick(object sender, MouseEventArgs e) {
int clickedIndex = checkedListBox1.IndexFromPoint(e.X, e.Y);
if (clickedIndex != -1) {
checkedListBox1.SetItemChecked(clickedIndex, !checkedListBox1.GetItemChecked(clickedIndex));
Debug.WriteLine("LEFT: MouseClick Selected Index: " + clickedIndex);
}
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e) {
Debug.WriteLine(" LEFT -> Item: " + (checkedListBox1.SelectedItem == null ? "Null" : checkedListBox1.SelectedItem));
Debug.WriteLine(" LEFT -> Index: " + checkedListBox1.SelectedIndex);
}
private void checkedListBox_NoSelect1_SelectedIndexChanged(object sender, EventArgs e) {
Debug.WriteLine("RIGHT -> Item: " + (checkedListBox_NoSelect1.SelectedItem == null ? "Null" : checkedListBox_NoSelect1.SelectedItem));
Debug.WriteLine("RIGHT -> Index: " + checkedListBox_NoSelect1.SelectedIndex);
}
I hope this makes sense and helps. Sorry that I did this in C#. If you can not convert the code to a VB version, then let me know and I will add a VB version.
Current screenshot:
I'd like to format the displayed value in the datagridview in the picture to two decimals, i wanted to make the change at display so i still have my orignal values untouched.
I've tried it placing the format in code
before, (At Form's New Sub)
after assigning the datagridview's datasource, (at Form's New Sub)
and also placing it in the designer, (datagridviewtextboxcolumn.defaultcellstyle)
still the values in the datagridview didnt change
You can put this in form load:
dataGridView.Columns["Total"].DefaultCellStyle.Format = "N2";
OR
private void dataGridView_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == indexOfColumn)
{
e.CellStyle.Format = "N2";
}
}
I have a form created in VB.net. It is used to get some information form a user. The form is not bound to any data source.
A combobox on this form is used to enter a cost. I want the value entered by the user to be displayed using currency format. I have used the Format String Dialog that opens from the ellipses button on the FormatString property of the combobox and selected Currency. This put C2 into the FormatString property.
When I run my application, this format is not applied to the value entered into the combobox at the time the number is entered or when I leave the combobox.
What am I missing?
Set the FormattingEnabled Property to True.
The FormatString property works only for data-bound controls. However, the input in a control can still be formatted with the ToString() method on a Change or Leave event.
The code sample below will format the text in the combo box to the default currency once the focus leaves control. Error handling can be done in the else clause:
private void comboBox1_Leave(object sender, EventArgs e)
{
string s = comboBox1.Text;
decimal result;
if (Decimal.TryParse(s, out result))
{
comboBox1.Text = result.ToString("C2");
}
}
Like the title says, I've got a Child form being shown with it's TopLevel property set to False and I am unable to click a MaskedTextBox control that it contains (in order to bring focus to it). I can bring focus to it by using TAB on the keyboard though.
The child form contains other regular TextBox controls and these I can click to focus with no problems, although they also exhibit some odd behavior: for example if I've got a value in the Textbox and I try to drag-click from the end of the string to the beginning, nothing happens. In fact I can't use my mouse to move the cursor inside the TextBox's text at all (although they keyboard arrow keys work).
I'm not too worried about the odd TextBox behavior, but why can't I activate my MaskedTextBox by clicking on it?
Below is the code that shows the form:
Dim newReportForm As New Form
Dim formName As String
Dim FullTypeName As String
Dim FormInstanceType As Type
formName = TreeView1.SelectedNode.Name
FullTypeName = Application.ProductName & "." & formName
FormInstanceType = Type.GetType(FullTypeName, True, True)
newReportForm = CType(Activator.CreateInstance(FormInstanceType), Form)
Try
newReportForm.Top = CType(SplitContainer1.Panel2.Controls(0), Form).Top + 25
newReportForm.Left = CType(SplitContainer1.Panel2.Controls(0), Form).Left + 25
Catch
End Try
newReportForm.TopLevel = False
newReportForm.Parent = SplitContainer1.Panel2
newReportForm.BringToFront()
newReportForm.Show()
I tried your code and got a good repro this time. As I mentioned in my original post, this is indeed a window activation problem. You can see this in Spy++, note the WM_MOUSEACTIVATE messages.
This happens because you display the form with a caption bar. That convinces the Windows window manager that the window can be activated. That doesn't actually work, it is no longer a top-level window. Visible from the caption bar, it never gets drawn with the "window activated" colors.
You will have to remove the caption bar from the form. That's best done by adding this line to your code:
newReportForm.FormBorderStyle = Windows.Forms.FormBorderStyle.None
Which will turn the form into a control that's otherwise indistinguishable from a UserControl. You can still make it distinctive by using this code instead:
newReportForm.ControlBox = False
newReportForm.Text = ""
Either fix solves the mouse click problem.
This is a miserable bug and it took me a long time to find this question. We're doing exactly the same thing as the OP, displaying a Form inside a split container. My workaround was to add an event handler to the MaskedTextBox's Click event:
private void MaskedTextBoxSetFocus(object sender, EventArgs e)
{
var mtb = (MaskedTextBox)sender;
mtb.Focus();
}
This works for the MaskedTextBox but I'm concerned about other odd behavior due to this bug so I will probably set the border style as in the accepted answer.
The text box behavior is a symptom of the same problem. Something is swallowing mouse down notifications. It isn't explained by your code snippet. Forms indeed swallow the mouse click that activates them, but that is a one-time behavior and is turned off by setting its TopLevel property to False.
Not much left. One candidate is the Control.Capture property, turned on at the MouseDown event for a button so that the button can see the MouseUp event, no matter where the mouse moved. That's a one-time effect as well. Watch out for controls that set the Focus in a MouseDown event.
The other is some kind of IMessageFilter code in your form(s) that's eating WM_LBUTTONDOWN messages.
I need to use a RichTextBox, not a normal textbox because of the way it keeps the caret position, from line to line. But I need to keep the text in the same font all the time even if it is pasted.
At the moment I have it selecting the entire text and changing the font to the original (Lucida Console) but it look horrible when you paste into it as it flashes blue.
If you are handling the pasting programatically don't use the Paste method. Instead use Clipboard.GetDataObject().GetData(DataFormats.Text) to get the text in a string and then add the text using the Rtf or Text property to the RichTextBox:
string s = (string)Clipboard.GetDataObject().GetData(DataFormats.Text);
richTextBox.Text += s;
Otherwise you could handle the Ctrl+V key press:
void RichTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.Control == true && e.KeyCode == Keys.V)
{
string s = (string)Clipboard.GetDataObject().GetData(DataFormats.Text);
richTextBox.Text += s;
e.Handled = true; // disable Ctrl+V
}
}
Darin's method ignores caret position and always appends to the end of text.
Actually, there are better method. Use overload of RichTextBox.Paste():
DataFormats.Format plaintext_format = DataFormats.GetFormat(DataFormats.Text);
this.Paste(plaintext_format);
Works like charm for me.
Both #Darin & #idn's answers are good, however I could get neither to work when pasting the following rich text:
This is text after an arrow.
This is a new line
The font would always change to WingDings. I had copied this from MS Word:
Specifically, the plain-text format method described by #idn above did indeed just paste plain text, but something was happening in which the font was changed too.
The following code handles the KeyUp event to just select all text and replace its original colours and font (i.e. formatting). To ensure that this isn't visible on the screen as a flicker, a special method of disabling window repaint events was employed. Control draw disablement occurs in the KeyDown event, the RichTextBox control handles the paste event by itself, and then Control drawing is re-enabled at the end. Finally, this only happens for CTL+V and SHIFT+INS, both of which are standard paste commands:
/// <summary>
/// An application sends the WM_SETREDRAW message to a window to allow changes in that
/// window to be redrawn or to prevent changes in that window from being redrawn.
/// </summary>
private const int WM_SETREDRAW = 11;
private void txtRichTextBox_KeyDown(object sender, KeyEventArgs e)
{
// For supported Paste key shortcut combinations, suspend painting
// of control in preparation for RTF formatting updates on KeyUp
if ((e.Control && !e.Shift && !e.Alt && e.KeyCode == Keys.V) || // CTL+V
(!e.Control && e.Shift && !e.Alt && e.KeyCode == Keys.Insert)) // SHIFT+INS
{
// Send Suspend Redraw message to avoid flicker. Drawing is
// restored in txtRichTextBox_KeyUp event handler
// [this.SuspendLayout() doesn't work properly]
Message msgSuspendUpdate = Message.Create(
txtRichTextBox.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);
NativeWindow window = NativeWindow.FromHandle(txtRichTextBox.Handle);
window.DefWndProc(ref msgSuspendUpdate);
}
}
private void txtRichTextBox_KeyUp(object sender, KeyEventArgs e)
{
// Following supported Paste key shortcut combinations, restore
// original formatting, then resume painting of control.
if ((e.Control && !e.Shift && !e.Alt && e.KeyCode == Keys.V) || // CTL+V
(!e.Control && e.Shift && !e.Alt && e.KeyCode == Keys.Insert)) // SHIFT+INS
{
// Layout already suspended during KeyDown event
// Capture cursor position. Cursor will later be placed
// after inserted text
int selStart = txtRichTextBox.SelectionStart;
int selLen = txtRichTextBox.SelectionLength;
// Replace all text with original font & colours
txtRichTextBox.SelectAll();
txtRichTextBox.SelectionFont = txtRichTextBox.Font;
txtRichTextBox.SelectionColor = txtRichTextBox.ForeColor;
txtRichTextBox.SelectionBackColor = txtRichTextBox.BackColor;
// Restore original selection
txtRichTextBox.SelectionStart = selStart;
txtRichTextBox.SelectionLength = selLen;
txtRichTextBox.ScrollToCaret();
// Resume painting of control
IntPtr wparam = new IntPtr(1); // Create a C "true" boolean as an IntPtr
Message msgResumeUpdate = Message.Create(
txtRichTextBox.Handle, WM_SETREDRAW, wparam, IntPtr.Zero);
NativeWindow window = NativeWindow.FromHandle(txtRichTextBox.Handle);
window.DefWndProc(ref msgResumeUpdate);
txtRichTextBox.Invalidate();
txtRichTextBox.Refresh();
}
}
A caveat of this approach is that, because the events are not suppressed (e.Handled = true;), the standard CTL+Z (undo) operation is supported. However this process cycles through undoing the format changes too. I don't see this as a big problem, because the next time that text is pasted, formatting is once again removed.
This approach isn't perfect, because if the text is copied and pasted from the RichTextBox (into another application), the newly applied formatting remains, but in my opinion, that's better than losing the undo functionality. If the undo functionality isn't important, then replace the text selection and formatting application with a replacement of the text to remove all formatting, as per this answer: https://stackoverflow.com/a/1557270/3063884
var t = txtRichTextBox.Text;
txtRichTextBox.Text = t;