我有一个接收Guid
的字符串变量。我需要将此字符串转换回Guid,因为数据库字段的类型为Guid
。
我尝试使用:
Guid myGuid = Guid.Empty;;
myGuid = Guid.Parse(myId);
但继续获得Format Exception; Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
。
以下是我的代码:
public string addVehicleDetails(string vname, string vtype, string regNumber, string ftype, string fefficiency, string insby, DateTime datecreated, string myId)
{
string result = string.Empty;
tblVehicleDetail myVehicleDetails = new tblVehicleDetail();
// Guid myGuid = Guid.Empty;
System.Guid myGuid = new Guid(myId);
// myGuid = Guid.Parse(myId);
try {
// Add details into vehicle details
myVehicleDetails.VehicleName = vname;
myVehicleDetails.VehicleType = vtype;
myVehicleDetails.RegistrationNumber = regNumber;
myVehicleDetails.FuelType = ftype;
myVehicleDetails.FuelEfficiency = fefficiency;
myVehicleDetails.InsuranceBy = insby;
myVehicleDetails.DateCreated = datecreated;
myVehicleDetails.Guid = myGuid;
dc.tblVehicleDetails.InsertOnSubmit(myVehicleDetails);
dc.SubmitChanges();
return result = vname;
}
catch(Exception exp)
{
exp.ToString();
return result = "Error in Adding Vehicle Details.";
}
}
对此有何解决方案?
答案 0 :(得分:0)
此Format Exception告诉您输入(String myId
)不是可识别的格式。
您应该清楚地处理异常输入字符串格式不正确所以使用Guid.TryParse
(如果输入为null或者不是以识别的格式,则此方法返回false,并且不会抛出异常。)。 Here
同时检查Guid.TryParseExact方法。
myGuid = Guid.Parse(myId);
if (Guid.TryParse(myId, out newGuid))
{
try
{
myVehicleDetails.DateCreated = datecreated;
myVehicleDetails.Guid = myGuid;
dc.tblVehicleDetails.InsertOnSubmit(myVehicleDetails);
dc.SubmitChanges();
}
}
else
{
//Input string is not in correct format
}