Load image from datagridview c# - c#

Im trying to fill a DataGridView with the value coming from my database. There is one column that has a value of a BLOB or image. Now when I'm loading it to the DataGridView it shows an error: Parameter is not valid. Can someone help me about this?
Triggering the method
private void Form1_Load(object sender, EventArgs e)
{
//load company to datagrid
string company = "SELECT * from tbl_payroll_company";
payroll.FillDataGrid(company, payroll_company_datagrid);
}
Method for filling my datagrid
public void FillDataGrid(string query,DataGridView gridview)
{
dbcon.Initialize();
if (dbcon.OpenCon() == true)
{
dt = new DataTable();
adapter = new MySqlDataAdapter(query, dbcon.con);
adapter.Fill(dt);
gridview.DataSource = dt;
dbcon.con.Close();
}
}
Here's how i saved it
private void btnCompanyUpload_Click(object sender, EventArgs e)
{
OpenFileDialog CompanyFileDialog = new OpenFileDialog();
if(CompanyFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
Image logo = Bitmap.FromFile(CompanyFileDialog.FileName);
payroll_company_logo.Image = logo;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void btnCompanySave_Click(object sender, EventArgs e)
{
if(dbcon.OpenCon() == true)
{
MemoryStream stream = new MemoryStream();
if (payroll_company_logo.Image != null)
{
payroll_company_logo.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
byte[] logo = stream.ToArray();
string[] column_name = {"payroll_company_logo"};
string table = "tbl_payroll_company";
string[] column_value = {logo.ToString()};
dbcon.Insert(table,column_name,column_value);
}
}
public void Insert(string table,string[] columns,string[] values)
{
this.Initialize();
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO " + table + "(" + string.Join(",", columns) + ") VALUES('" + string.Join("','", values) + "')", con);
int check = cmd.ExecuteNonQuery();
con.Close();
}
ERROR

Related

How can i insert changes from datagridview to database?

As you can read from header, i had a problem with insert from datagridview. Here code of my shiny probram:
namespace LibrarianApp
{
public partial class Start : Form
{
public Start()
{
InitializeComponent();
Start_Load();
}
private static DataTable GetData(string SQLiteCommand)
{
string conString = "Data Source=Books.db;Version=3;";
SQLiteConnection cnn = new SQLiteConnection(conString);
SQLiteCommand command = new SQLiteCommand(SQLiteCommand, cnn);
SQLiteDataAdapter adapter = new SQLiteDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
private void Start_Load()
{
dataGridView1.DataSource = GetData("select * from Books where BookName like '%" + NameTextBox.Text + "%' and AuthorName like '%" + AuthorTextBox.Text + "%' and Genre like '%" + GenreTextBox.Text + "%'");
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
dataGridView1.BorderStyle = BorderStyle.Fixed3D;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns["ID"].Visible = false; dataGridView1.Columns["BookName"].HeaderText = "Название"; dataGridView1.Columns["AuthorName"].HeaderText = "Автор";
dataGridView1.Columns["Genre"].HeaderText = "Жанр"; dataGridView1.Columns["Amount"].HeaderText = "Количество в наличии";
}
private void SearchButtom_Click(object sender, EventArgs e)
{
Start_Load();
}
private void AddBookButtom_Click(object sender, EventArgs e)
{
AddBookForm AddDialog = new AddBookForm();
AddDialog.Show();
}
private void RefreshButtom_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = GetData("select * from Books");
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
dataGridView1.BorderStyle = BorderStyle.Fixed3D;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns["ID"].Visible = false; dataGridView1.Columns["BookName"].HeaderText = "Название"; dataGridView1.Columns["AuthorName"].HeaderText = "Автор";
dataGridView1.Columns["Genre"].HeaderText = "Жанр"; dataGridView1.Columns["Amount"].HeaderText = "Количество в наличии";
}
private void InsertFromGridButtom_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
string conString = "Data Source=Books.db;Version=3;";
using (SQLiteConnection conn = new SQLiteConnection(conString))
{
using (SQLiteCommand comm = new SQLiteCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text + ", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch
{
}
}
}
}
As you can see i use datagridview datasourse straight from the .db file. And i think, that why i got that error: "DataGridViewCell" does not contain definition for 'Text'"
https://ibb.co/1M4YkZX
How can i fix this?

Drawing image in listview

I'm trying to make this catalog app that display images with its "title" and "category" but I can't seem to display the image because of an error
on the line that says
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
This is the whole of my code. I need the solution so i can print the image with its corresponding details in a list view. Thank you.
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Books");
comboBox1.Items.Add("Games");
comboBox1.Items.Add("Music");
}
SqlConnection connection = new SqlConnection("Data Source=DESKTOP-4T5BLQ6\\SQLEXPRESS;Initial Catalog=CatalogDB;Integrated Security=True");
SqlCommand command = new SqlCommand();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlDataReader dataReader;
DataTable dataTable = new DataTable();
MemoryStream stream1;
byte[] photo_array;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
int i = 0;
MemoryStream stream = new MemoryStream();
command.CommandText = "insert into EntryTable(Title,Category,Image) values('" + textBox1.Text + "','" + comboBox1.Text + "','" + pictureBox1.Image + "')";
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
if (i > 0)
{
MessageBox.Show("Saved new item in index" + i);
}
connection.Close();
MessageBox.Show("Made New Entry");
showData();
clear();
}
void clear()
{
textBox1.Clear();
pictureBox1.Image = null;
comboBox1.SelectedIndex = -1;
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Images only. |*.jpg; *jpeg; *.png; *.gif; *.bmp;";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
private void showData()
{
connection.Open();
listView1.Clear();
ImageList images = new ImageList();
images.ColorDepth = ColorDepth.Depth32Bit;
listView1.LargeImageList = images;
listView1.LargeImageList.ImageSize = new System.Drawing.Size(100 , 100);
command.Connection = connection;
command.CommandText = "SELECT * FROM EntryTable";
dataAdapter.SelectCommand = command;
dataTable.Clear();
dataAdapter.Fill(dataTable);
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
connection.Close();
}
}
}
Xoriel,
You need to be more specific about what you are asking on SO. Your original post only indicates that you have and error and that it is holding up your app development (welcome to coding). You don't even tell us what error you are getting.
Now you ask how to implement a try catch? You should do a bit of research on your own. As far as try catch, you can start Here.
Your code indicates a lack of understanding about how windows winforms are instantiated and their sequence of events. To me, this indicates that you will have further problems after this one is fixed, so I will add a try catch to your code. It will write the exception to your console.
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
try
{
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
Your true issue is the format in which you are storing the image to the database and the way in which you are retrieving it.
Regards,
Marc

Upload documents to Access DB using c#

I am working in Visual Studio 2010 and I am trying to upload documents via a webpage to an access database. I am not getting any errors when I run my code, but nothing is writing to the database. Here is my on click code to show what I think it is supposed to do.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExtension = Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".doc" || fileExtension.ToLower() != ".docx" || fileExtension.ToLower() != ".pdf")
{
lblInfo.Text = "Only .doc, .docx, or .pdf files are allowed.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
int fileSize = FileUpload1.PostedFile.ContentLength;
if (fileSize > 2097152)
{
lblInfo.Text = "Maximum file size of 2 MB exceeded.";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
else
{
OleDbCommand update = new OleDbCommand("Update STAFF SET Resume = #Resume WHERE StaffID=#StaffID", DBConnection);
update.Parameters.Add("#Resume", OleDbType.LongVarBinary).Value = FileUpload1.FileContent;
update.Parameters.Add("#StaffID", OleDbType.Integer).Value = txtStaffID.Text;
lblInfo.Text = "File Uploaded";
lblInfo.ForeColor = System.Drawing.Color.Green;
}
}
}
else
{
lblInfo.Text = "Please select a file to upload";
lblInfo.ForeColor = System.Drawing.Color.Red;
}
}
If you could provide any advice or suggestions that would be great. Thanks. I will show the entirety of the code also, just in case it's an issue with the DB connection.
public partial class Staff : System.Web.UI.Page
{
OleDbConnection DBConnection = new OleDbConnection();
OleDbDataAdapter DataAdapter;
DataTable LocalDataTable = new DataTable();
private void ConnectToDatabase()
{
DBConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\CIS470_TPS_System\CIS470_TPS_System\CIS470_TPS_System\App_Data\TpsSystem_DB.mdb";
DBConnection.Open();
DataAdapter = new OleDbDataAdapter("Select * From STAFF", DBConnection);
DataAdapter.Fill(LocalDataTable);
}
private void Page_Load(object sender, EventArgs e)
{
ConnectToDatabase();
}
protected void AccessDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string requestId = GridView1.SelectedRow.Cells[1].Text;
txtSelectedStaff.Text = requestId; //this control holds the selected value
}
protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
}
As suggested in the comments to the question, we can use the FileUpload control's .FileBytes property to supply the value of the query parameter, as in this (simplified) example:
protected void btnUpload_Click(object sender, EventArgs e)
{
using (var con = new OleDbConnection())
{
con.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\staffDb.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
"UPDATE STAFF SET Resume=? " +
"WHERE StaffID=?";
cmd.Parameters.AddWithValue("?", FileUpload1.FileBytes);
cmd.Parameters.AddWithValue("?", 1);
cmd.ExecuteNonQuery();
}
con.Close();
}
}

How do i get my picture to show up to picturebox1 when i click my datagridview row in c#

I have a this program that if a user clicks a row in the datagridview:
private void ListView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (!ListView.Rows[e.RowIndex].IsNewRow)
{
idnum.Text = ListView.Rows[e.RowIndex].Cells[0].Value.ToString();
CmbPosition.Text = ListView.Rows[e.RowIndex].Cells[1].Value.ToString();
TxtFirstName.Text = ListView.Rows[e.RowIndex].Cells[2].Value.ToString();
TxtMiddleName.Text = ListView.Rows[e.RowIndex].Cells[3].Value.ToString();
TxtLastName.Text = ListView.Rows[e.RowIndex].Cells[4].Value.ToString();
CmbYearLevel.Text = ListView.Rows[e.RowIndex].Cells[5].Value.ToString();
CmbCourse.Text = ListView.Rows[e.RowIndex].Cells[6].Value.ToString();
TxtSchoolYear.Text = ListView.Rows[e.RowIndex].Cells[7].Value.ToString();
TxtFilePath.Text = ListView.Rows[e.RowIndex].Cells[8].Value.ToString();
BtnAdd.Enabled = false;
}
else
{
ClearData();
}
}
catch
{
}
}
and to read the database so it can get the path and show up the image that i saved in the database to picturebox1 whenever a user clicked a row in the datagridview.
public void TabindexChanged()
{
MemoryStream ms = new MemoryStream();
cmd = new SqlCommand("SELECT * FROM DBAdmin WHERE imgPath='" + _dg + "'", sc);
sc.Open();
SqlDataReader dr;
try
{
dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] picarr = (byte[])dr["imgImage"];
ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
_pb.Image = Image.FromStream(ms);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
but it seems that it wont get the imgPath from the database..
does not show up any picture in the picturebox1 whenever a row is selected.
Thanks in advance.

c# save data from datagridview to database

I would like to edit my database record from datagridview and save from there. What properties do i need to declare to enable me to edit the datagrid? And button2 is my save button, how do i update to the database? Someone please help me thanks!
{
//Get ID
string strTagIds = string.Empty;
//Connection to datebase
string c1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection con = new OleDbConnection(c1);
}
private void button1_Click(object sender, EventArgs e)
{
//button1.Click += new EventHandler(dataGridView1_CellContentClick);
//Bind button
string txt = textBox1.Text;
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
string strSqlStatement = string.Empty;
strSqlStatement = "SELECT * FROM jiahe WHERE [User] = '" + txt + "'";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSqlStatement, objConnection);
DataSet ds = new DataSet();
objAdapter.Fill(ds);
DataTable dt = ds.Tables[0];
dataGridView1.DataSource = dt.DefaultView;
try
{
if (dt.Rows.Count == 1)
{
string strLine = string.Empty;
string strUser = string.Empty;
foreach (DataRow dr in dt.Rows)
{
string strTags = dr["Tag ID"].ToString();
strUser = dr["User"].ToString();
string strAge = dr["Age"].ToString();
string strPhoneNumber = dr["Phone Number"].ToString();
// prepare command string
string selectString = #"SELECT Status FROM jiahe where [User] = '" + textBox1.Text + "'";
// 1. Instantiate a new command with command text only
OleDbCommand cmd = new OleDbCommand(selectString, objConnection);
// 2. Set the Connection property
cmd.Connection.Open();
// 3. Call ExecuteScalar to send command
string str = cmd.ExecuteScalar().ToString();
cmd.Connection.Close();
}
}
else
{
if (dt.Rows.Count == 0)
{
MessageBox.Show("Invalid input!");
}
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, EventArgs e)
{
//dataGridView1.BeginEdit(true);
//MessageBox.Show("Hello");
}
private void button2_Click(object sender, EventArgs e)
{
}
You need datagridview cell content value changed. You should make a string which will be updated each time you edit a row with the ID/index of the selected row. Then you can make an update to the database when the button2 is clicked.

Categories

Resources