kostyavechkanov
kostyavechkanov

Reputation: 28

Get PropertyGrid TextBox

How can I get PropertyGrid's TextBox from specified field? I need this TextBox to set Pointer to the end of text.

var num = txtBox.GetCharIndexFromPosition(Cursor.Position);
txtBox.SelectionStart = num + 1;
txtBox.SelectionLength = 0;

So how can I get this TextBox from PropertyGrid? Also, property in PropertyGrid is read-only.

Upvotes: 0

Views: 982

Answers (1)

user2480047
user2480047

Reputation:

If what you want is the cursor to be located right after the last character written in the textbox, you can rely on the following code (triggered by the TextChanged Event of the TextBox):

private void txtBox_TextChanged(object sender, EventArgs e)
{
    int newX = txtBox.Location.X + TextRenderer.MeasureText(txtBox.Text, txtBox.Font).Width;
    int newY = txtBox.Bottom - txtBox.Height / 2;
    if (newX > txtBox.Location.X + txtBox.Width)
    {
        newX = txtBox.Location.X + txtBox.Width;
    }
    Cursor.Position = this.PointToScreen(new Point(newX, newY));
}

Bear in mind that its Y position is always in the middle.

----- UPDATE AFTER THE KINGKING COMMENT

As far as the code in the question was referred to the TextBox, I focused my answer on the TextBox. Nonetheless, KingKing is right and the PropertyGrid has to be brought into consideration. Below these lines I adapted the code you can find in MSDN for PropertyGrid:

private void Form1_Load(object sender, EventArgs e)
{
    PropertyGrid propertyGrid1 = new PropertyGrid();
    propertyGrid1.CommandsVisibleIfAvailable = true;
    propertyGrid1.Location = new Point(10, 20);
    propertyGrid1.Size = new System.Drawing.Size(400, 300);
    propertyGrid1.TabIndex = 1;
    propertyGrid1.Text = "Property Grid";

    this.Controls.Add(propertyGrid1);

    propertyGrid1.SelectedObject = txtBox;
}

After txtBox is added to propertyGrid1, its position is updated and thus the original code can be used without any problem.

In summary, the idea is not looking for the TextBox inside the PropertyGrid, but accessing directly the TextBox control (which is added at runtime to the PropertyGrid).

Upvotes: 1

Related Questions