开发者

Set value to DataGridTextBoxCell in DataGridView

开发者 https://www.devze.com 2023-03-02 02:55 出处:网络
I\'m trying to safe users from error message by check if user entered more then maximum allowed size to my DataGridViewCell.

I'm trying to safe users from error message by check if user entered more then maximum allowed size to my DataGridViewCell.

I'm making :

private void dataGridView3_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 1)
    {
        st开发者_JAVA技巧ring selected = (dataGridView3[e.RowIndex, 1] as DataGridViewTextBoxCell).FormattedValue.ToString();
        if (selected.Length > 50)
        {
            dataGridView3[e.RowIndex, 1].Value = selected.Take(50).ToString();
        }
    }
}

selected is my text but , I've got error message on updating : Can't convert string to int32... and if I use = 0 it just makes no sense. What's wrong here ?

Error is coming when I updating texbox with Length > 50 , it says that my value is not integer. But it must be a string. I just readed a string from the same cell.


You misplace rows and columns in

dataGridView3[e.RowIndex, 1]

it should be column first, then row:

dataGridView3[1, e.RowIndex]

Besides, do you have to do casting on DataGridViewTextBoxCell? It works for me:

string selected = dataGridView3[1, e.RowIndex].FormattedValue.ToString();

And my sugesstion: why use it in CellEndEdit, not in CellValidating event? You could then simplify to:

e.FormattedValue.ToString()

Edit Cell validating is fired more frequent than EndEdit: even on cell selection change. If it's not OK for you, then rather stay with CellEndEdit as you did. And, as mentioned, make sure datasource holds string, not integer. By the way: in my VS there is no Take() function , I replaced it with Substring(), try like this:

private void dataGridView3_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 1)
    {
        string selected = dataGridView3[1, e.RowIndex].FormattedValue.ToString();

        if (selected.Length > 50)
        {
            dataGridView1[3, e.RowIndex].Value = selected.Substring(0, 50);
        }
    }
}


You have to Cast the String to a correct Integer value. You are trying to set a Integer value with a String, and it cannot do the conversion.

0

精彩评论

暂无评论...
验证码 换一张
取 消