Delete Selected Text from Textbox and Enter New Char in C#.NET - c#-4.0

I am trying to delete selected text from textbox and enter new character in place of it.
For example, if textbox consists of 123456 and I select 345, and press r on the keyboard, it should replace the selected text.
here is my code:
string _selectText = txtCal.SelectedText;
string _text = Convert.ToString(btn.Text);
if (_selectText.Length > 0) {
int SelectionLenght = txtCal.SelectionLength;
string SelectText = txtCal.Text.Substring(txtCal.SelectionStart, SelectionLenght);
txtCal.Text = ReplaceMethod(SelectText, _text);
}
//replace method function
public string ReplaceMethod(string replaceString, string replaceText) {
string newText = txtCal.Text.Replace(replaceString, replaceText);
return newText;
}
Can anyone show me where my mistake is?

The replace-based answer offered above may well replace the wrong instance of the selection, as noted in the comments. The following works off positions instead, and doesn't suffer that problem:
textbox1.Text = textbox1.Text.Substring(0, textbox1.SelectionStart) + textbox1.Text.Substring(textbox1.SelectionStart + textbox1.SelectionLength, textbox1.Text.Length - (textbox1.SelectionStart + textbox1.SelectedText.Length));

The following does what you want and then selects the replacing text :)
string _text = Convert.ToString(btn.Text);
int iSelectionStart = txtCal.SelectionStart;
string sBefore = txtCal.Text.Substring(0, iSelectionStart);
string sAfter = txtCal.Text.Substring(iSelectionStart + txtCal.SelectionLength);
txtCal.Text = sBefore + _text + sAfter;
txtCal.SelectionStart = iSelectionStart;
txtCal.SelectionLength = _text.Length;

Try this instead
if (textbox1.SelectedText.Length > 0)
{
textbox1.Text = textbox1.Text.Replace(text1.Text.Substring(textbox1.SelectionStart, textbox1.SelectionLength), btn.Text);
}

This is essentially the same as other answers, but formatted differently using C# 6.0.
// If there is selected text, it will be removed before inserting new text.
// If there is no selected text, the new text is inserted at the caret index.
string before = textBox.Text.Substring(0, textBox.SelectionStart);
string after = textBox.Text.Substring(textBox.SelectionStart + textBox.SelectedText.Length);
textBox.Text = $"{before}{insertText}{after}";
textBox.CaretIndex = $"{before}{insertText}".Length;
Note that I set the CaretIndex to a new position after changing the text. This may be useful since the caret index resets to zero when changing the text like this. You may also want to focus the textbox to draw the user's attention to the change and allow them to know where the caret currently is.

Related

Matlab Justify Strings

I'm using Matlab R2014b (that's why I cannot use strings, but only char vectors). Working inside a class, I have to take data from a table variable, format it following my needs, and then insert it into a GUI table (an instance of uitable, to be exact):
function UpdateTable(this)
siz = size(mydata);
tab = cell(siz);
tab(:,1) = num2cell(this.Data.ID);
tab(:,2) = cellstr(datestr(this.Data.Date,'dd/mm/yyyy'));
tab(:,3) = arrayfun(#(x){MyClass.TypeDef1{x,1}},this.Data.Type1);
tab(:,4) = arrayfun(#(x){MyClass.TypeDef2{x,1}},this.Data.Type2);
tab(:,5) = arrayfun(#(x){MyClass.FormatNumber(x)},this.Data.Value);
this.UITable.Data = tab;
end
Where:
properties (Access = private, Constant)
TypeDef1 = {
'A1' 'Name A1';
'B1' 'Name B1';
'C1' 'Name C1';
'D1' 'Name D1';
...
}
TypeDef2 = {
'A2' 'Name A2';
'B2' 'Name B2';
'C2' 'Name C2';
'D2' 'Name D2';
...
}
end
methods (Access = private, Static)
function str = FormatNumber(num)
persistent df;
if (isempty(df))
dfs = java.text.DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
dfs.setGroupingSeparator('.');
df = java.text.DecimalFormat();
df.setDecimalFormatSymbols(dfs);
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
end
str = char(df.format(num));
end
end
Everything is working fine. Now I would like to right justify the strings to be inserted in columns 1 and 5, to improve the table readability. I found the Matlab function that suits my needs, strjust. Reading the documentation, I saw that it can be used with cell arrays of char vectors, so I modified part of my UpdateTable code as follows:
tab(:,1) = cellstr(num2str(this.Data.ID));
tab(:,5) = strjust(arrayfun(#(x){MyClass.FormatNumber(x)},this.Data.Value));
TThe second one produces no changes (strings are still not justified). Should the strings already contain enough whitespace to be all the same length?
Ok, I solved the problem by myself using the following code:
function UpdateTable(this)
siz = size(this.Data);
los = arrayfun(#(x){MyClass.FormatNumber(x)},this.Data.Value);
los_lens = cellfun(#(x)numel(x),los);
pad = cellfun(#blanks,num2cell(max(los_lens) - los_lens),'UniformOutput',false);
tab = cell(siz);
tab(:,1) = cellstr(num2str(this.Data.ID));
tab(:,2) = cellstr(datestr(this.Data.Date,'dd/mm/yyyy'));
tab(:,3) = arrayfun(#(x){MyClass.TypeDef1{x,1}},this.Data.Type1);
tab(:,4) = arrayfun(#(x){MyClass.TypeDef2{x,1}},this.Data.Type2);
tab(:,5) = cellstr(strcat(pad,los));
this.UITable.Data = tab;
end
It's probably not the most elegant solution, but it works. Starting from Matlab 2016, the padding can be performed using the built-in pad function.

Access to value of a Table Item

I am doing a Vaadin project and maybe it's easy question but my brain is stop working right now.
I have a Table which code is like:
Table table = new Table();
table.addContainerProperty("Value", String.class, "");
table.addContainerProperty("combo", ComboBox.class, null);
table.addItem(new Object[]{"asd123", combo1}, 1);
table.addItem(new Object[]{"asd1234", combo2}, 2);
combo1 and combo2 are ComboBoxes, their code is like:
ComboBox combo1 = new ComboBox();
combo1.addItem("Choice 1");
combo1.addItem("Choice 2");
ComboBox combo2 = new ComboBox();
combo2.addItem("Girls");
combo2.addItem("Boys");
I want to access an item on table, and hold this as String.
Assume that there is a String str and String str2 variables, and I want that (str = asd123) and (str2 = combo2's selected element).
How can I do that?
If you can help, I appreciate that.
table.getItem(itemId);
// or
combo2.getValue();
However, these functions both return Object values so you have to typecast them to String before using them properly.
String str = (String) table.getItem(itemId);
For further reference see Vaadin Table and Vaadin ComboBox.

windows phone 8 string split into three parts

Hi i want to set a text to three textblocks from service url
"http://www.findyourfate.com/rss/yearly-horoscope.asp?sign=Aries",which is a single string,
I just want to split three strings and setting the text to three textblocks of
text1,text2,text3.idone setting why i'm splitting means in single textblock not displaying full content because of this reason i thought to split into three strings.for first text block what i neede to display has been done sucessfulyy ,I tried to set for rest of the textblock but i'm stuck please help me to resolve this issue.I'm begginer to this windows 8 development please help me.
try
{
XDocument xmlDoc = XDocument.Parse(e.Result);
var result = xmlDoc.Descendants("channel");
List<xmlList> _xmList = new List<xmlList>();
foreach (var item in result)
{
var node = item.Descendants("item");
//XDocument xdoc = XDocument.Load(e.Result);
foreach (var xElememt in node)
{
string description = xElememt.Element("description").Value;
MessageBox.Show("" + description.Length);
string input = description;
int pattern = input.IndexOf("CAREER");
int pattern1 = input.IndexOf("RELATIONSHIP");
int pattern2 = input.IndexOf("FINANCE");
string str1 = input.Substring(0,pattern);
string str2 = input.Substring(pattern,pattern1);
string str3 = input.Substring(pattern2);
text1.Text = str1;
text2.Text = str2;
text3.Text = str3;
}
You could use the String.Split Method in order to split a string.
Reference: C# Split A String By Another String
You don't have need to split the string and also no need to use three textblocks,
You can use RichTextBox control to show the information.
It will show your full content of description
use the bellow code with scrollbar in .xaml page
<ScrollViewer
VerticalScrollBarVisibility="Visible"
ManipulationMode="Control"
Height="400"
Margin="0,0,0,-13" >
<RichTextBox TextAlignment="Justify"
IsReadOnly="True"
Margin="0,0,0,10">
<Paragraph Foreground="#626262"
FontSize="17"
FontStyle="Normal"
FontFamily="Regular" >
<Run x:Name="txtDescription" />
</Paragraph>
</RichTextBox>
</ScrollViewer>
and set the value of description to txtDescription in .xaml.cs file
txtDescription.Text = xElememt.Element("description").Value;

AS3 Using a variable with Transform

I have a text field and a background and want to apply color using
myColorPicker. Either the text field or background can be selected using
radioGroup1. When either radio button is selected the trace statement
traces the variable obj2Clr exactly. However when I use that variable
with Transform, I can't apply color. If I hard code and use the actual
object then it works.
Can I not use a variable with Transform or is something else missing?
My code is below:
var radioGroup1:RadioButtonGroup = new RadioButtonGroup("selObj");
bkg_rb.label = "Background";
text_rb.label = "Text";
bkg_rb.group = radioGroup1;
text_rb.group = radioGroup1;
var obj2Clr;//which object to apply color to
radioGroup1.addEventListener(MouseEvent.CLICK, getObj);
function getObj(e:MouseEvent):void {
if (bkg_rb.selected == true) {
obj2Clr = "MovieClip(parent).design_mc.bkg_mc";
trace(obj2Clr);
} else if (text_rb.selected == true) {
obj2Clr = "MovieClip(parent).design_mc.info_txt";
trace(obj2Clr);
}
}
var colorTrans:ColorTransform = new ColorTransform();
var trans:Transform = new Transform(obj2Clr);
//var trans:Transform = new Transform(MovieClip(parent).design_mc.info_txt);
myColorPicker.addEventListener(ColorPickerEvent.CHANGE, changeColor);
function changeColor(event:ColorPickerEvent):void {
var myColor = "0x" + event.target.hexValue;
colorTrans.color = myColor;
trans.colorTransform = colorTrans;
trace("color selected is " + myColor);
}
Thanks for your help in advance:)
Debbie D
According to this code, obj2Clr is being initialized with a string literal?
For example, shouldn't this snippet:
if (bkg_rb.selected == true) {
obj2Clr = "MovieClip(parent).design_mc.bkg_mc";
trace(obj2Clr);
}
be:
if (bkg_rb.selected == true) {
obj2Clr = MovieClip(parent).design_mc.bkg_mc;
trace(obj2Clr);
}
?
Thanks, yes I thought I had to use a string literal with Transform because tracing out the variable without quotes that make it a literal resulted in [object MovieClip] and [object TextField].
So I removed the quotes and Transform still is not receiving the new Transform object. Yet when I hard code (which was commented out in the above example) everything is fine. Any other area I should check?
Debbie D :)

Why does calling the YUI Datatable showCellEditor not display the editor?

Clicking on the second cell (any row) in the datatable causes the cell editor to display. But, I am trying to display the cell editor from code. The code looks like the following:
var firstEl = oDataTable.getFirstTdEl(rowIndex);
var secondCell = oDataTable.getNextTdEl(firstEl);
oDataTable.showCellEditor(secondCell);
When I debug into the datatable.js code (either with a click or from the code above) it follows the same path through the showCellEditor function but the above code will not display the editor.
I am using YUI version 2.8.0r4.
I think this is blur events issue.
So, for example, I have link that must add record to datatable, and show its editor.
var mymethod = function (e) {
YAHOO.util.Event.stopEvent(e);
var r = {};
r.id = 0;
r.value = 'hello world';
myDataTable.addRow(r);
var cell = myDataTable.getLastTrEl().cells[0];
myDataTable.showCellEditor(cell);
}
YAHOO.util.Event.addListener('mylink2addrecord_ID', 'click', mymethod);
Without stopEvent you will never see editor, because there is tableBlur event called when you click on yourlink....
You can try this - this is ONLY a snippet from a larger piece of an event handler set of code I have. EditNext is the function that moves over a cell and displays the editor, if the cell has one:
this.myDataTable.subscribe("editorKeydownEvent",function(oArgs) {
var self = this,
ed = this._oCellEditor, // Should be: oArgs.editor, see: http://yuilibrary.com/projects/yui2/ticket/2513909
ev = oArgs.event,
KEY = YAHOO.util.KeyListener.KEY,
Textbox = YAHOO.widget.TextboxCellEditor,
Textarea = YAHOO.widget.TextareaCellEditor,
DCE = YAHOO.widget.DateCellEditor,
cell = ed.getTdEl(),
col = ed.getColumn(),
row,rec,
editNext = function(cell) {
cell = self.getNextTdEl(cell);
while (cell && !self.getColumn(cell).editor) {
cell = self.getNextTdEl(cell);
}
if (cell) {
self.showCellEditor(cell);
}
},
As mac said, you need to stop the previous event. For some reason it (the tableBlur event) conflicts with the showCellEditor function. This is the first place which had a resolution to the problem.
To sum it up, all I did was:
YAHOO.util.Event.stopEvent(window.event);<br/>
dt.showCellEditor(td); // dt = yui datatable obj, td = {record: yuirecord, column: yuicolumn}
Of course if you have the event object readily available as mac's post does, you can pass it to stopEvent(e) like he did.

Resources