如何从C#代码设置GUID字段

时间:2012-05-04 17:54:05

标签: c# asp.net ado.net guid sqldatasource

InsertParameters中有一个参数。当我尝试设置它时,我收到错误::

  

不允许从数据类型sql_variant到uniqueidentifier的隐式转换。使用CONVERT函数运行此查询

这是我在c#中的代码:

String complexID = Guid.NewGuid().ToString();
SqlDataSource1.InsertParameters["PKComplexID"].DefaultValue = complexID;

有人可以帮忙吗?

5 个答案:

答案 0 :(得分:1)

您需要更改SqlDbType上的Inserting

protected void SqlDataSource1_Inserting(object sender, 
  SqlDataSourceCommandEventArgs e) { 
    SqlParameter insertedKey = 
      e.Command.Parameters["@PKComplexID"] as SqlParameter; 
    insertedKey.SqlDbType = SqlDbType.UniqueIdentifier; 
}

<强>参考

http://forums.asp.net/t/1712791.aspx/1

  

对象是uniqueidentifier字段的错误类型。但不幸的是   我们在VisualStudio设计器中没有uniqueidentifier。所以这是   给你输入Object。你也不能把它作为uniqueidentifier   抛出你的例外。所以你必须改变这个参数类型表格   dataSource_Inserting事件中的代码隐藏文件。确保它的插入   事件。在那里,您可以获取任何参数并设置uniqueidentifier   字段类型为uniqueidentifier。

GUIDs and DataSource Controls

答案 1 :(得分:1)

我还没有尝试过,但我的第一反应是:

Guid complexID = Guid.NewGuid();
SqlDataSource1.InsertParameters["PKComplexID"].DefaultValue = complexID;

答案 2 :(得分:0)

您不应该转换为字符串。像这样修复你的代码:

Guid complexID = Guid.NewGuid(); 

答案 3 :(得分:0)

我刚刚将参数类型从object更改为string。它解决了。

答案 4 :(得分:0)

试试这个

 string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Guid id=Guid.NewGuid();
FileUpload1.SaveAs(Server>MapPath("Your Path"+id+fileName ));