Datagridview cell mouseClick event error - c#

can you help me to this problem
i have one form production from where i can upload that photo and save it on to the database,
but when i do a cellmouseclick event it having some problem
and below is the code for doing so:
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
SqlDataReader dr;
private void button2_Click(object sender, EventArgs e)
{
byte[] image = null;
FileStream fs = new FileStream(this.txtLink.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
image = br.ReadBytes ((int)fs.Length);
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto,Photo) Values(#IDProduksi,#IDPhoto,#TanggalProduksi,#NamaKaryawan,#KeteranganPhoto,#Photo)", con);
cmd.Parameters.AddWithValue("#IDProduksi", txtIdpro.Text);
cmd.Parameters.AddWithValue("#IDPhoto", txtIdPhoto.Text);
cmd.Parameters.AddWithValue("#TanggalProduksi", dProduksi);
cmd.Parameters.AddWithValue("#NamaKaryawan", txtNamaKaryawan.Text);
cmd.Parameters.AddWithValue("#KeteranganPhoto", rxtKtrphoto.Text);
cmd.Parameters.AddWithValue("#Photo", image);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
txtIdpro.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
txtIdPhoto.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
dtmProduksi.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
txtNamaKaryawan.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
rxtKtrphoto.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
txtLink.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
// wanna show that picture when you klik cell
byte[] imgg = (byte[])(dr["Photo"]);
MemoryStream Strem = new MemoryStream(imgg);
pictureBox1.Image = System.Drawing.Image.FromStream(Strem);
}
and if i commend that byte[] that can be like that below :
and if i commend that byte[] that can be like that below :

You need to initialize dr. You must create in dataGridView1_CellMouseClick a select query and than you can do this:
dr = cmd.ExecuteReader();
while (dr.Read()) { }

Related

"Parameter is not valid" error when retrieving image

I want to retrieve images from a SQL Server database using C#. However, I'm getting the error message
Parameter is not valid
Please help me.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string q = "select * from Rough where name='" + comboBox1.Text + "'";
SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=SMS_DB;Integrated Security=True");
SqlCommand cmd = new SqlCommand(q, con);
SqlDataReader dr;
if (con.State == ConnectionState.Closed)
{
con.Open();
dr = cmd.ExecuteReader();
byte[] img = null;
while (dr.Read())
{
textBox1.Text = (dr["ID"].ToString());
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Image"].ToString());
img = (byte[])(dr["Image"]);
if (img == null)
{
pictureBox2.Image = null;
}
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox2.Image = Image.FromStream(ms);
// ms.Close();
}
}
con.Close();
}
}

c# how to get selectedindex and do a sql query

I am trying to get the selectedindex of listbox 1 and 2 and update my databasetable based on the values selected in the two listboxes, but can't find a way to get the selectedindexes into my sql statement. Any suggestions?
private void Form1_Load(object sender, EventArgs e)
{
String cs = "Database=something;User=-;Password=-";
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter(
"select * from reservasjon WHERE Rom_nr IS NULL ", dbconn);
adapter.Fill(ds);
this.listBox1.DataSource = ds.Tables[0];
this.listBox1.DisplayMember = "Rnr";
}
private void button1_Click(object sender, EventArgs e)
{
String cs = "Database=something;User=-;Password=-";
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
DataSet ds2 = new DataSet();
MySqlDataAdapter adapter2 = new MySqlDataAdapter(
"select * from rom WHERE etasje = '1' AND opptatt='1'", dbconn);
adapter2.Fill(ds2);
this.listBox2.DataSource = ds2.Tables[0];
this.listBox2.DisplayMember = "Rom_nr";
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value1 = listBox1.SelectedIndex.ToString();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string value2 = listBox2.SelectedIndex.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
string value1 = listBox2.Text;
string value2 = listBox1.Text;
MySqlDataReader dr = null;
try
{
String cs = "Database=something;User=-;Password=-";
string selectStatement = "UPDATE reservasjon SET Rom_nr='102' WHERE Rnr='2';";
System.Data.DataTable dt = new System.Data.DataTable();
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
MySqlDataAdapter sqlDa = new MySqlDataAdapter();
sqlDa.SelectCommand = new MySqlCommand(selectStatement, dbconn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Rnr"] = "";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
}
catch (Exception s)
{
Console.WriteLine(s.Message);
}
}
This should do the trick :
private void button4_Click(object sender, EventArgs e)
{
string value1 = listBox2.Text;
string value2 = listBox1.Text;
MySqlDataReader dr = null;
try
{
String cs = "Database=something;User=-;Password=-";
string selectStatement = "UPDATE reservasjon SET Rom_nr='"+value2+"' WHERE Rnr='"value1+"';";
System.Data.DataTable dt = new System.Data.DataTable();
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
MySqlDataAdapter sqlDa = new MySqlDataAdapter();
sqlDa.SelectCommand = new MySqlCommand(selectStatement, dbconn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Rnr"] = "";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
}
catch (Exception s)
{
Console.WriteLine(s.Message);
}
}
That's cause your variable value1 and value2 is not available outside the event handler method since you made them local. Declare them globally or just use the listBox1.SelectedIndex.ToString() directly in your SQL query

displaying images on crystalreport

This is my code,i want display images that stored in sql to crystal reports,please someone help me :)
private void button2_Click(object sender, EventArgs e)
{
string connectionstring = null;
SqlConnection conn;
connectionstring="Server=AJITHBABU\\SQLEXPRESS;Initial Catalog=temprorary;User ID=sa;Password=2604";
conn=new SqlConnection(connectionstring);
byte[] img = null;
FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
k = "INSERT INTO temprorary4(id,img)values('" + textBox1.Text + "',#img)";
conn.Open();
cmd = new SqlCommand(k, conn);
cmd.Parameters.Add(new SqlParameter("#img",img));
int x=cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show(x.ToString() +"record(s) saved");
}

Cannot reuse open DataReader

I am writing a c# windows forms application and i am coming accross the error mentioned above. I think this is happening because i am opening an sql connection and reader object in my main form load object and then doing the same thing again in another click event handler. I am not sure what i need to do in order to change my code / stop this from happening (or if this is even the problem). I have tried turning MARS on in my connection string but this did not fix the problem. Below is my code.
namespace Excel_Importer
{
public partial class Export : Form
{
public Export()
{
InitializeComponent();
}
private void cmbItemLookup_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Export_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings ["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From ExportItem", conn);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("ExportItemName", typeof(string));
dt.Load(rdr);
cmbItemLookup.DisplayMember = "ExportItemName";
cmbItemLookup.DataSource = dt;
conn.Close();
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn);
SqlDataReader rdr2;
rdr2 = cmd2.ExecuteReader();
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
You need to close your DataReaders. They implement the IDisposable interface, so the simplest thing is to put them inside a using block:
using (rdr = cmd.ExecuteReader())
{
..
} // .NET always calls Dispose() for you here
Actually, you pretty much have to dispose of everything that implements IDisposable, or problems gonna happen.
As the other answer points out, you must tidy up your clicked event code:
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString) )
{
conn.Open();
using(SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn) )
{
using(SqlDataReader rdr2= cmd2.ExecuteReader())
{
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
}

Retrieve Image from Binary Data in SQL to DataList

I am doing a 3 tier application to retrieve image from sql server which i stored image to binary data in sql, and the problem is i can't retrieve my image from the sql server.
here is my code in DataAccessLayer
public List<Volunteer> VolunteerTRetrieve()
{
List<Volunteer> vList = new List<Volunteer>();
byte[] volunteerProfilePicture;
string volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact;
string queryStr = "SELECT * FROM TVolunteer Order By VolunteerName";
SqlConnection conn = new SqlConnection(DBconnStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while ((dr.Read()))
{
volunteerName = dr["VolunteerName"].ToString();
volunteerNRIC = dr["VolunteerNRIC"].ToString();
volunteerAddress = dr["VolunteerAddress"].ToString();
volunteerEmail = dr["VolunteerEmail"].ToString();
volunteerContact = dr["VolunteerContact"].ToString();
volunteerProfilePicture = (byte[])dr["VolunteerProfilePicture"];
vList.Add(new Volunteer(volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact, volunteerProfilePicture));
}
conn.Close();
dr.Dispose();
return vList;
}
in BusinessLogicLayer
public List<Volunteer> RetrieveAllBVolunteer()
{
Volunteer v = new Volunteer();
List<Volunteer> vList = new List<Volunteer>();
vList = v.VolunteerBRetrieve();
return vList;
}
and in PresentationLayer
List<Volunteer> allVolunteer = new List<Volunteer>();
allVolunteer = vBLL.RetrieveAllTVolunteer();
dl_tvolunteer.DataSource = allVolunteer;
dl_tvolunteer.DataBind();
I have also an image handler class
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DBconnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string queryStr = "SELECT VolunteerProfilePicture FROM TVolunteer WHERE VolunteerNRIC = #NRIC";
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.Add("#NRIC", SqlDbType.VarChar).Value =
context.Request.QueryString["VolunteerNRIC"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["VolunteerProfilePicture"]);
}
Please help, Thankyou!
If you are returning one image you could the following
1. place a PictureBox control on the asp.net webpage
2. define the sql connections //not sure why you are using cmd.prepare
byte[] sqlImage = (byte[])cmd.ExecuteScalar();
MemoryStream memStream = new MemoryStream();
memStream.Write(sqlImage, 0, sqlImage.Length);
Bitmap bit = new Bitmap(memStream);
or if you want to do it a different way
try
{
con = new SqlConnection(constr);
cmd = new SqlCommand("select photopath,Photo from employees where employeeid=14", con);
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if (!dr.IsDBNull(1))
{
byte[] photo = (byte[])dr[1];
MemoryStream ms = new MemoryStream(photo);
pictureBox1.Image = Image.FromStream(ms);
}
}
}
catch (Exception ex)
{
dr.Close();
cmd.Dispose();
con.Close();
Response.Write(ex.Message);
}

Categories

Resources