Reputation: 29
I want to delete data from database using aa ListBox in a C# WinForm application. I am trying this code but it is not working. Please tell me how can I delete data from ListBox
it is giving me this error
Conversion failed when converting the varchar value 'System.Data.DataRowView' to data type int.
string i= listBox1.SelectedItem.ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
con.Open();
SqlCommand CmdAddProof = new SqlCommand("delete from Tb_IdProof where PID='" + i+ "'", con);
CmdAddProof.CommandType = CommandType.Text;
CmdAddProof.ExecuteNonQuery();
textBox1.Text = string.Empty;
ShowProof();
con.Close();
Upvotes: 0
Views: 778
Reputation: 35925
There are a few things you can improve:
This is likely to fix your problem.
EDIT
If you use parametrised command, you pass it a type, so that the driver knows how to handle and escape the type. When you embed a variable into a query, a .ToString()
method gets called. There can be many bugs due to incorrect assumption that string representation corresponds to what you expect it to be. In this case, this will work. But! In other cases it may not work. Such bugs are really difficult to debug, as they appear only in certain cases.
You may choose to say that application is only going to speak to a local server. Never ever it is going to be exposed to the network. Then you change your job and application suddenly becomes very successful and exposed to the Internet. And guess what?
If only you had applied defensive codding by default, you could have saved yourself from many troubles.
Always assume that environment is hostile, user input is evil and trust no one. Feel free to disagree, you have been warned.
Upvotes: 0
Reputation: 446
Is it manually generated or data bound;
If manually generated use
listBox1.Items.Remove(i);
If databound you need to refresh your binding in that case.
Regards Jan.
Upvotes: 0
Reputation: 16433
If PID
is an int
data type you will get a data conversion error because you are passing in your ID value as a varchar
not an int
.
Removing the single quotes from your command text will fix it:
SqlCommand CmdAddProof = new SqlCommand("delete from Tb_IdProof where PID=" + i, con);
Edit following further comments by user
As it transpires that the ListBox
is actually data bound, you are receving the error because the SelectedItem
property is giving you back a DataRowView
instead of a value.
You will need to obtain the value for the PID
column from the DataRowView
object before you call your SqlCommand
.
Upvotes: 3