GrayFox
GrayFox

Reputation: 1089

DataGridTextColumn Readonly behaviour like TextBox

I need a way to let the DataGridTextColumn's readonly behaves like the textbox's ones:

If a textbox is readonly you can click in the field and select the text and have a context menu with right click.

If a DataGridTextColumn is readonly you can't click in and select the words and you don't have a context menu.

I want the look like a DataGridTextColumn, how can I solve my problem?

Thanks in advance!!

Upvotes: 1

Views: 627

Answers (2)

Dave M
Dave M

Reputation: 3043

Use a DataGridTemplateColumn instead, and put a ready only TextBox as the data template.

<DataGridTemplateColumn Header="My Property" IsReadyOnly="True" SortMemberPath="MyProperty">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox Text="{Binding MyProperty}" IsReadOnly="True"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Upvotes: 2

John
John

Reputation: 3702

Your best bet is using the EditingControlShowing event. In the code below, there is a 2 column datagrid added to the form. Both are basic textbox columns. By attaching the EditingControlShowing event, you can modify the properties of the Editing control used.
In this example i set the control read-only if it's column 1 (the value col) and read-write for column 0.
Mind the fact that the EditingControl is actually a DataGridViewTextBoxEditingControl, a subclass to TextBox.

public partial class Form2 : Form
{
    class Item
    {
        public string Label { get; set; }
        public string Value { get; set; }
    }

    DataGridView _dgv;

    public Form2()
    {
        InitializeComponent();

        _dgv = new DataGridView();
        _dgv.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dgv_EditingControlShowing);
        _dgv.DataSource = GetData();

        Controls.Add(_dgv);
    }

    void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        var dgv = (DataGridView)sender;
        if (e.Control is TextBox)
        {
            var tb = (TextBox)e.Control;
            tb.ReadOnly = (dgv.CurrentCell.ColumnIndex == 1);
        }
    }

    private BindingList<Item> GetData()
    {
        var result = new BindingList<Item>();
        result.Add(new Item { Label = "Lbl 1", Value = "Val 1" });
        result.Add(new Item { Label = "Lbl 2", Value = "Val 2" });
        result.Add(new Item { Label = "Lbl 3", Value = "Val 3" });
        return result;
    }
}

Upvotes: 1

Related Questions