specified cast is not valid
-
02 Mei 2012 10:21I've got an error message that "specified cast is not valid".
let me explane it in details.
my Library database have a table named Borrower, here it is.
USE [Library]
GO
/****** Object: Table [dbo].[Borrowers] Script Date: 05/01/2012 20:57:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Borrowers](
[BorrowerID] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[BorrowerName] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Department] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[BorrowerLevel] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Session] [varchar](15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_Borrowers] PRIMARY KEY CLUSTERED
(
[BorrowerID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
/// my insertion code using DLINQ
LibraryDataContext ldc = new LibraryDataContext();
private void save_Click(object sender, RoutedEventArgs e)
{
Borrower b = new Borrower();
b.BorrowerID = borrowerID.Text;
b.BorrowerLevel = borrowerLebel.SelectedItem.ToString();
b.BorrowerName = borrowerName.Text;
b.Department = departmentName.SelectedItem.ToString();
b.Session = session.SelectedItem.ToString();
try
{
ldc.Borrowers.InsertOnSubmit(b);
ldc.SubmitChanges();
MessageBox.Show(b.BorrowerName + " Successfully inserted","Successfully Inserted");
this.clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error borrower saving! ");
}
}
///
and I got an error message saying "specified cast is not valid."
So what should i do ?
Semua Balasan
-
03 Mei 2012 5:06Moderator
Hi Arefin Sami,
Welcome to MSDN Forum.
Could you please clarify which line throws the exeption? I create the table with your sql script and execute the code you posted, Inserting is successful, no exception was thrown.
Best Regards
Allen Li [MSFT]
MSDN Community Support | Feedback to us
-
07 Mei 2012 6:30Moderator
Hi Arefin Sami,
Have you solved the issue? I look forward to hearing from you.
Best Regards
Allen Li [MSFT]
MSDN Community Support | Feedback to us
-
07 Mei 2012 7:15
Try the forum from the neighbors The Linq to SQL one, this is the DataSet forum
http://social.msdn.microsoft.com/Forums/en-US/linqtosql/threads
Success
Cor -
11 Juni 2012 14:17
Hi,
This may be a long shot but I noticed you have three lines that look like they are taking values from comboboxes:
b.BorrowerLevel = borrowerLebel.SelectedItem.ToString();
b.Department = departmentName.SelectedItem.ToString();
b.Session = session.SelectedItem.ToString();These won't work as they'll return the Type rather than the value selected i.e. the Type of the object. Try "SelectedText" instead.
That may be why you're seeing the specified cast exception.
Chris