can i dynamically set a reference to a form control?

  • Thread starter Thread starter Dica
  • Start date Start date
D

Dica

i want to allow my "Cut" command to dynamically determine the active control
and cut any selected text from it (assuming it's a textBox control). so far
i've got this:

private void menuItem5_Click(object sender, System.EventArgs e)

{

Object oControlType =
System.Windows.Forms.Form.ActiveForm.ActiveControl.GetType();

if (oControlType.ToString() == "System.Windows.Forms.TextBox")

{

oActiveControl = System.Windows.Forms.Form.ActiveForm.ActiveControl;

if(oActiveControl.SelectedText != "")

{

oActiveControl.Cut();

}

}

}



i want to set oActiveControl to the active textBox and cut any text, but
this doesn't work. is there a way to pull this off or do i have to first
determine exactly which textBox is active and then cut from there?



tks
 
Dica,

You should be able to do something like this:

// Get the control.
object control = System.Windows.Forms.Form.ActiveForm.ActiveControl;

// Try to cast to a textbox.
TextBox textBox = control as System.Windows.Forms.TextBox;

// If the textbox exists, then work with it.
if (textBox != null)
{
// Do your cut and paste operation here.
}

The "as" operator will attempt to cast the variable before it (in this
case "control") to the type that comes after it. If it succeeds, it returns
the typed result, otherwise it returns null (it returns null if the variable
is null as well).

Hope this helps.
 
Nicholas Paldino said:
Dica,

You should be able to do something like this:

// Get the control.
object control = System.Windows.Forms.Form.ActiveForm.ActiveControl;

// Try to cast to a textbox.
TextBox textBox = control as System.Windows.Forms.TextBox;

// If the textbox exists, then work with it.
if (textBox != null)
{
// Do your cut and paste operation here.
}

The "as" operator will attempt to cast the variable before it (in this
case "control") to the type that comes after it. If it succeeds, it returns
the typed result, otherwise it returns null (it returns null if the variable
is null as well).

Hope this helps.

works like a charm. tks nicholas.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Dica said:
i want to allow my "Cut" command to dynamically determine the active
control
and cut any selected text from it (assuming it's a textBox control). so
far
i've got this:

private void menuItem5_Click(object sender, System.EventArgs e)

{

Object oControlType =
System.Windows.Forms.Form.ActiveForm.ActiveControl.GetType();

if (oControlType.ToString() == "System.Windows.Forms.TextBox")

{

oActiveControl = System.Windows.Forms.Form.ActiveForm.ActiveControl;

if(oActiveControl.SelectedText != "")

{

oActiveControl.Cut();

}

}

}



i want to set oActiveControl to the active textBox and cut any text, but
this doesn't work. is there a way to pull this off or do i have to first
determine exactly which textBox is active and then cut from there?



tks
 
Back
Top