开发者

c# DataColumn: generate a new GUID as default value?

开发者 https://www.devze.com 2023-03-19 18:41 出处:网络
My problem: I have a DataSet with multiple DataTables in it. All of these DataTables have a DataColumn named \"Id\" with a DataType of System.Guid.

My problem:

I have a DataSet with multiple DataTables in it. All of these DataTables have a DataColumn named "Id" with a DataType of System.Guid.

A short example of such a table:

+--------------------+
| User               |
+--------------------+
| *Id as System.Guid |
| Username as String |
| /* more columns */ |
+--------------------+

I assigned this DataTable to a DataGridView. The DataGridView is configured to allow creating, editing and deletion of entries.

When a user now creates a new entry and saves it, there is an exception that the "Id" is unset.

My question:

How is it possible to automatically generate a new System.Guid for new entries?

My current thoughts:

  • Specifying some magic value in dataSet.dataTable.Columns['Id开发者_如何学运维'].DefaulValue . (Something like the <DBNull>)
  • Using something like a trigger on dataSet.dataTable listening for new rows. It would have to get executed before the row gets validated
  • Same thing like the trigger, but on the dataGridView.

What I've tried:

  • These events of the DataGridView: RowsAdded, UserAddedRow, RowValidating, DefaultValuesNeeded

It would be awesome if anyone would have a working solution or a hint for me!

~Chris


I'm not sure why you say you cannot use DefaultValuesNeeded - I've just tested this and it works perfectly:

void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
    e.Row.Cells["Guid"].Value = Guid.NewGuid();
}

I set the visibility property of the Guid column to false so that it doesn't show. When a new row is created the row has a guid populated.


Yeah, just use the appropriate event and add the GUID value to the correct column. If the column is visible to the user then you could add it when the user clicks in one of the cells for the new row. Perhaps the RowsAdded event will do the job

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowsadded.aspx


I was hoping to use the DefaulValue to simplify things and replace my current solution, but after reading this thread it looks like I cannot.

My current solution is to have the [ID] column in the DataGridView (Visible = false) and add the new GUID if it is missing on the DataGridView RowValidating event.

    private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        try
        {
            //If ID is empty create a new GUID
            Guid guidID = Guid.NewGuid();
            if (this.dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString() == "")
                this.dataGridView1.Rows[e.RowIndex].Cells[2].Value = guidID;

        }
        catch { }
    }
0

精彩评论

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