问题
I am working on WinForms using C#. I made a class video that has method yourvideos()
. This method reads data from SQL database and add it in imagelist
and listview
.
First I have uploaded the image and then take the location of image using:
var=open.FileName.ToString();
Then in a function uploadvideo()
, I converted image to bytearray and inserted it to database:
public void uploadvideo(string url, string path, string name,string title, DateTime date, string imgloc, string user)
{
con.Open();
FileStream file = new FileStream(imgloc,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(file);
byte[] img = br.ReadBytes((int)file.Length);
cmd = new SqlCommand($"insert into RecipeInfo (RecipeName, [Recipe Link],Thumbnail,Username, Date, Title) values ('{name}','{path}','@img','{user}','{date}','{title}')", con);
cmd.ExecuteNonQuery();
}
and then the function yourvideos()
where I am retrieving data comes.
public void yourvideos(string user, ImageList imglist, ListView list, Label l)
{
cmd = new SqlCommand($"select Title, Thumbnail from RecipeInfo where username='{user}'", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.HasRows)
{
byte[] img = (byte[])(reader[2]);
MemoryStream ms = new MemoryStream(img);
imglist.Images.Add(Image.FromStream(ms));
list.Items.Add(reader[5].ToString());
//MessageBox.Show("Data presesnt");
}
}
else
{
l.Visible = true;
l.Text = "Upload videos and share your recipes with others";
}
reader.Close();
con.Close();
}
This function is called in the Form under the button click event
v1.yourvideos(Form2.setname, imageList1, yourvideoslistview, messagelabel);
Now, the issue is that the control enter in if statement means data is present but then it does not read data and display error:
Invalid attempt to read when no data is present.
How can I solve this issue? I showed a messagebox in order to confirm that the if statement is working and it worked, but data is not being retrieved.
回答1:
Firstly, not looking to fix your method in obtaining your data, as there are a number of issues here but you can get help on these in other SO Q's.
You can't return an index in position 5 when you are only selecting 2 columns of data.
list.Items.Add(reader[5].ToString());
Change this to something like:
list.Items.Add(reader["Title"].ToString());
Substitute 'Title' for anything else in your SELECT statement.
I would also change:
while (reader.HasRows)
To
while(reader.Read())
EDIT In order to fix up part of your SQL statement which will not work, I would suggest using a SQL Command Parameter. First, update this part of your Query.
username='{user}'
to this
username = @username
Next, you will need to set this as a command parameter by adding the following on the line before con.Open().
cmd.Parameters.AddWithValue("@username", user);
来源:https://stackoverflow.com/questions/63695972/invalid-attempt-to-read-when-no-data-is-present