[英]How do I access a Control type variable's possible properties?
I have a Control type variable that will be set to either a combo box or a text box.I cannot access the selection start property from the control variable. 我有一个控件类型变量,它将被设置为组合框或文本框。我无法从控件变量访问选择开始属性。 This must be because that data type is a parent to controls that do not have that property.
这必须是因为该数据类型是不具有该属性的控件的父级。 How can I get around this to access the selection start property?
如何解决此问题以访问选择开始属性?
The code: 编码:
private void createText(string lowerCaseChar, string upperCaseChar)
{
Control FocusedTextComboBox;
switch (lastTextComboBoxFocused)
{
case 54:
FocusedTextComboBox = SearchTextBox;
break;
case 4:
FocusedTextComboBox = VendorComboBox;
break;
case 6:
FocusedTextComboBox = VendorComboBox;
break;
case 5:
FocusedTextComboBox = DeptComboBox;
break;
}
if (SearchTextBox.SelectionStart == 0 && SearchTextBox.Text != "")
{
switch (shift)
{
case true:
FocusedTextComboBox.Text += upperCaseChar;
break;
case false:
FocusedTextComboBox.Text += lowerCaseChar;
break;
}
}
else
{
int SelectionStartNumber = FocusedTextComboBox.SelectionStart;
switch (shift)
{
case true:
FocusedTextComboBox.Text = FocusedTextComboBox.Text.Insert(FocusedTextComboBox.SelectionStart, upperCaseChar);
break;
case false:
FocusedTextComboBox.Text = FocusedTextComboBox.Text.Insert(FocusedTextComboBox.SelectionStart, lowerCaseChar);
break;
}
FocusedTextComboBox.SelectionStart = SelectionStartNumber + 1;
}
FocusedTextComboBox.Focus();
}
You are correct that it is a data type issue. 您是正确的,这是一个数据类型问题。 You need to cast the
object
type to textbox
to be able to access the selection start property. 您需要将
object
类型转换为textbox
,才能访问选择开始属性。
if(FocusedTextComboBox is TextBox)
SelectionStartNumber = (FocusedTextComboBox as TextBox).SelectionStart
Extending user3529814's answer, declare a local variable as a TextBox and cast your control so you can use it throughout the block: 扩展user3529814的答案,将局部变量声明为TextBox并转换控件,以便可以在整个块中使用它:
if (FocusedTextComboBox is TextBox)
{
TextBox tb = (TextBox)FocusedTextComboBox;
if (SearchTextBox.SelectionStart == 0 && SearchTextBox.Text != "")
{
switch (shift)
{
case true:
tb.Text += upperCaseChar;
break;
case false:
tb.Text += lowerCaseChar;
break;
}
}
else
{
int SelectionStartNumber = tb.SelectionStart;
switch (shift)
{
case true:
tb.Text = tb.Text.Insert(tb.SelectionStart, upperCaseChar);
break;
case false:
tb.Text = tb.Text.Insert(tb.SelectionStart, lowerCaseChar);
break;
}
tb.SelectionStart = SelectionStartNumber + 1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.