Updating Database Using Datagridview - c#

I can add, edit, delete database using listbox. But I want to do it using DatagridView I already bind it to my database.
How do I add,edit,delete update my database in datagridview using codes?
These are my codes:
namespace Icabales.Homer
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\homer\documents\visual studio 2010\Projects\Icabales.Homer\Icabales.Homer\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
SqlDataAdapter da;
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}
private void bindgrid()
{
string command = "select * from info";
da = new SqlDataAdapter(command, cn);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.info' table. You can move, or remove it, as needed.
this.infoTableAdapter.Fill(this.database1DataSet.info);
cmd.Connection = cn;
loadlist();
bindgrid();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "")
{
cn.Open();
cmd.CommandText = "insert into info (id,name) values ('" + txtid.Text + "' , '" + txtname.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record Inserted");
cn.Close();
txtid.Text = "";
txtname.Text = "";
loadlist();
}
}
private void loadlist()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "select * from info";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
txtid.Text = listBox1.SelectedItem.ToString();
txtname.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "")
{
cn.Open();
cmd.CommandText = "delete from info where id = '"+txtid.Text+"'and name = '"+txtname.Text+"'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Deleted");
loadlist();
txtid.Text = "";
txtname.Text = "";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "" & listBox1.SelectedIndex != -1)
{
cn.Open();
cmd.CommandText = "update info set id='"+txtid.Text+"',name='"+txtname.Text+"'where id='"+listBox1.SelectedItem.ToString()+"' and name='"+listBox2.SelectedItem.ToString()+"'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Updated");
loadlist();
txtid.Text = "";
txtname.Text = "";
}
}
}
}

I have a dataGridView and a button on a form. When I do any editing, insertion or deletion in the dataGridView1, the code below does the magic
public partial class EditPermit : Form
{
OleDbCommand command;
OleDbDataAdapter da;
private BindingSource bindingSource = null;
private OleDbCommandBuilder oleCommandBuilder = null;
DataTable dataTable = new DataTable();
public EditPermit()
{
InitializeComponent();
}
private void EditPermitPermit_Load(object sender, EventArgs e)
{
DataBind();
}
private void btnSv_Click(object sender, EventArgs e)
{
dataGridView1.EndEdit(); //very important step
da.Update(dataTable);
MessageBox.Show("Updated");
DataBind();
}
private void DataBind()
{
dataGridView1.DataSource = null;
dataTable.Clear();
String connectionString = MainWindow.GetConnectionString(); //use your connection string please
String queryString1 = "SELECT * FROM TblPermitType"; // Use your table please
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = queryString1;
try
{
da = new OleDbDataAdapter(queryString1, connection);
oleCommandBuilder = new OleDbCommandBuilder(da);
da.Fill(dataTable);
bindingSource = new BindingSource { DataSource = dataTable };
dataGridView1.DataSource = bindingSource;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

I have implemented a solution that inserts/updates/deletes data in MS SQL database directly from DataGridView.
To accomplish this I have used the following events: RowValidating and UserDeletingRow.
It is supposed that you have
SqlConnection _conn;
declared and initialized.
Here is the code:
private void dgv_RowValidating( object sender, DataGridViewCellCancelEventArgs e )
{
try
{
if (!dgv.IsCurrentRowDirty)
return;
string query = GetInsertOrUpdateSql(e);
if (_conn.State != ConnectionState.Open)
_conn.Open();
var cmd = new SqlCommand( query, _conn );
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning );
}
}
public string GetInsertOrUpdateSql( DataGridViewCellCancelEventArgs e )
{
DataGridViewRow row = dgv.Rows[e.RowIndex];
int id = 0;
int.TryParse( row.Cells["Id"].Value.ToString(), out id );
DateTime dob;
DateTime.TryParse( row.Cells["Dob"].Value.ToString(), out dob );
string email = row.Cells["Email"].Value.ToString();
string phone = row.Cells["Phone"].Value.ToString();
string fio = row.Cells["Fio"].Value.ToString();
if (id == 0)
return string.Format( "insert into {0} Values ('{1}','{2}','{3}','{4}')", "dbo.People", fio, dob.ToString( "dd-MM-yyyy" ), email, phone );
else
return string.Format( "update {0} set Fio='{1}', Dob='{2}', Email='{3}', Phone='{4}' WHERE Id={5}", "dbo.People", fio, dob.ToString( "dd-MM-yyyy" ), email, phone, id );
}
private void dgv_UserDeletingRow( object sender, DataGridViewRowCancelEventArgs e )
{
try
{
int id = 0;
int.TryParse( e.Row.Cells["Id"].Value.ToString(), out id );
string query = string.Format( "DELETE FROM {0} WHERE Id = {1}", "dbo.People", id );
var cmd = new SqlCommand( query, _conn );
if (_conn.State != ConnectionState.Open)
_conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show( ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning );
}
}
Hope this helps.

I have the same kind of project at home, I do not have the source code with me but if needed I can check somewhere this weekend to see what exactly I have done, but I believe it's some of the following:
Since you are using a dataset and a dataadapter this can be achieved very easily.
As long as your DataGridView1 has the properties enabled for users to add/delete/edit rows you could use the following code.
DataAdapter.Update(DataTable);
//in your code this would be:
da.Update(dt);
The DataAdapter.Update() Method will auto generate any insert/update/delete commands needed to update the results of your fill query compared with the current data in your datagridview.
You can set those commands (properties) as well in case you prefer to modify them, though this is not necessary.
This only works ofcourse after a user has made changes to the DataGridView. Add this code to a simple button and see if you have any luck. It definitly was something this simple :)

Related

C# program reports "Index was outside the bounds of the array"

May I ask, how can I get error for this? It is so confusing. I get bug like this and I try to fix, but it does not work at all. I'm just a beginner.
namespace WindowsFormsApp1
{
public partial class Schedule : Form
{
public Schedule()
{
InitializeComponent();
}
MySqlConnection con = new MySqlConnection(#"Data Source=localhost;port=3306;Initial Catalog=Payroll;User Id=root;password=''");
MySqlDataReader dr;
int tc = 0;
private void Schedule_Load(object sender, EventArgs e)
{
datagrid();
fillsched();
}
public void datagrid()
{
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter("Select * from employee where Pstatus='Active'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
con.Close();
}
public void fillsched()
{
con.Open();
MySqlDataReader dr;
MySqlCommand cmd = new MySqlCommand("select * from updateschedule ", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
int data = dr.GetInt32("empSched");
comboBox1.Items.Add(data);
}
con.Close();
}
public void getsched()
{
if (Int32.TryParse(comboBox1.SelectedItem.ToString(), out tc))
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from updateschedule where empSched=#empSched ", con);
cmd.Parameters.Add("#empSched", MySqlDbType.Int32).Value = tc;
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr["TimeIn"].ToString();
textBox3.Text = dr["TimeOut"].ToString();
label5.Text = tc.ToString();//to pass the data in the combobox1
}
con.Close();
}
}
public void view()
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
getsched();
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
view();
}
}
private void button1_Click(object sender, EventArgs e)
{
insert();
insertempsched();
}
public void insert()
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule (empSchedID,empID,empIN,empOut)VALUES(#empSchedID,#empID,#empIn,#EmpOut)", con);
cmd.Parameters.Add("#empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("#empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.Parameters.Add("#empIn", MySqlDbType.Date).Value = textBox2.Text;
cmd.Parameters.Add("#empOut", MySqlDbType.VarChar).Value = textBox3.Text;
execnonquery(cmd, "Data Inserted");
}
public void insertempsched()
{
con.Open();
MySqlCommand cmd = new MySqlCommand("Update employee set empSched=empSched where empID=#empID", con);
cmd.Parameters.Add("#empSchedID", MySqlDbType.Int32).Value = label5.Text;
cmd.Parameters.Add("#empID", MySqlDbType.VarChar).Value = textBox1.Text;
cmd.ExecuteNonQuery();
con.Close();
}
public void execnonquery(MySqlCommand sqc, string mymsg)
{
con.Open();
if (sqc.ExecuteNonQuery() == 1)
{
MessageBox.Show(mymsg);
}
else
{
MessageBox.Show("Query not Executed");
}
con.Close();
}
}
}
"Index was outside the bounds of the array" in c# always indicates that you are trying to get values based on column index number or row index number from datagrid or datatables or arrays and column or row does not exist at that position or index.
I think you are getting error at following line which exists in "view" method.
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
Also to catch the errors it's a good practice to use try catch blocks in all the methods.
You can modify your method like this
public void view()
{
try
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Error by this code

When I fill out the form and click registration, it shows an error:
Object reference not set to an instance of an object.
The error is here:
int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
Which object must be added to refrence?
Here is the code of the web page:
public partial class register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
if(IsPostBack)
{
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
tring"].ConnectionString);
conn.Open();
string checkuser = "SELECT * FROM [Table] where user_name ='" +
Text_username + "'";
SqlCommand com = new SqlCommand (checkuser , conn);
int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1){
Response.Write("User already exists");
}
conn.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Text_fname.Text = "";
Text_lname.Text = "";
Text_email.Text = "";
Text_password.Text = "";
Text_password_again.Text = "";
Text_username.Text = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
tring"].ConnectionString);
conn.Open();
string insert = "insert into Table
(user_fname,user_lname,user_email,user_password,user_name) values (#firstName
,#lastName ,#Email ,#passWord ,#userName)";
SqlCommand com = new SqlCommand (insert , conn);
com.Parameters.AddWithValue("#firstName", Text_fname.Text);
com.Parameters.AddWithValue("#lastName", Text_lname.Text);
com.Parameters.AddWithValue("#Email", Text_email.Text);
com.Parameters.AddWithValue("#passWord", Text_password.Text);
com.Parameters.AddWithValue("#userName", Text_username.Text);
com.ExecuteNonQuery();
Response.Write("Registration is successful");
Response.Redirect("Default.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
}
}
From the error message you have posted, it is clear that the com.ExecuteScalar() is null. Hence, when you call the ToString method on it you get a null reference exception. Since the com.ExecuteScalar() can be null, I suggest you do a check for this.
int temp;
var result = com.ExecuteScalar();
if(result != null)
{
temp = Convert.ToInt32(result.ToString());
}
if (temp == 1)
{
Response.Write("User already exists");
}

Updating Datagridview data using SQLite Database

I'm having trouble updating data from a data grid view with the use of a button. The text is editable but the changes does not save to the SQLite database. any ideas?
private void ProjectsAdmin_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'seniorProjectsDataSet2.DataTable1' table. You can move, or remove it, as needed.
this.dataTable1TableAdapter.Fill(this.seniorProjectsDataSet2.DataTable1);
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1 || e.ColumnIndex != 3) //ignore header row and any column that doesnt have file name
return;
var filename = dataGridView1.CurrentCell.Value.ToString();
if (File.Exists(filename))
Process.Start(filename);
}
private void updateData_Click(object sender, EventArgs e)
{
SQLiteConnection conn = new SQLiteConnection();
dataGridView1.EndEdit();
dataTable1TableAdapter.Adapter.Update(seniorProjectsDataSet.Tables[0]);
for (int i = 0; i < seniorProjectsDataSet.Tables[0].Rows.Count; i++)
{
seniorProjectsDataSet.Tables[0].Rows[i].AcceptChanges();
}
}
}
}
I solved the problem without a Button. In the following code I´ll give you a example how the connection and the update works with a mysql-database (update in runtime):
CODE
DataTable dt = null;
DataGridView dgv1 = null;
If the form load you have to set your dt variable to a new datatable:
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select *from try.data ;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv1 = new DataGridView();
dgv1.AllowUserToAddRows = false;
dgv1.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv1.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv1.Dock = DockStyle.Fill;
dgv1.DataSource = dt;
this.Controls.Add(dgv1);
}
You have to set two events: CellValidating
private void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
InitializeComponent();
if (e.ColumnIndex == 0)
{
dgv1.CancelEdit();
}
}
and the CellValidating Event:
private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string id = dt.Rows[e.RowIndex]["Eid"] + "";
string col = dt.Columns[e.ColumnIndex].ColumnName;
string data = dgv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value + "";
string sql = string.Format("UPDATE `try`.`data` SET `{0}` = '{1}' WHERE Eid = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
This aktually works with MySql but in Sql are "Equal" components like the SqlConnection or the SqlCommand... I hope this solve you problem. Have a nice day!
using System.Data.SQLite;
SQLiteConnection con = new SQLiteConnection("Data Source=C:\\Cogs\\bin\\Release\\db\\my_database_file.db");
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [my_table]";
con.Open();
cmd.ExecuteNonQuery();
DataTable dta = new DataTable();
SQLiteDataAdapter dataadp = new SQLiteDataAdapter(cmd);
dataadp.Fill(dta);
dataGridView1.DataSource = dta;
con.Close();

C# Database Insert not working from textbox to listbox

I've made a library management system. Put 4 boxes containing the title, author, no of pages and publisher. And then add a button to add it on the database, and I also have 3 listboxes containing the title, author and publisher. It seems that when I accomplished filling up the 4 textboxes and then clicking the button for insert, it's not updating the listboxes and even the database. Nothing is happening. How do you do that?
OleDbCommand cmd = new OleDbCommand();
OleDbConnection cn = new OleDbConnection();
OleDbDataReader dr;
public frm1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database2.accdb;Persist Security Info=True";
cmd.Connection = cn;
loaddata();
}
private void loaddata()
{
lstbxTitle.Items.Clear();
lstbxAuthor.Items.Clear();
lstbxPub.Items.Clear();
try
{
string q = "SELECT * FROM Table2";
cmd.CommandText = q;
cn.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
lstbxTitle.Items.Add(dr[1].ToString());
lstbxAuthor.Items.Add(dr[2].ToString());
lstbxPub.Items.Add(dr[6].ToString());
}
}
dr.Close();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
private void lstbxTitle_Click(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
try
{
if (l.SelectedIndex != 1)
{
lstbxTitle.SelectedIndex = l.SelectedIndex;
lstbxAuthor.SelectedIndex = l.SelectedIndex;
lstbxAuthor.Text = lstbxAuthor.SelectedItem.ToString();
lstbxPub.SelectedIndex = l.SelectedIndex;
lstbxPub.Text = lstbxPub.SelectedItem.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtbxAddT.Text != "")
{
string q = "insert into Table2 (Title) values ('" + txtbxAddT.Text.ToString() + "')";
txtbxAddT.Text = null;
}
if (txtbxAddA.Text != "")
{
string q = "insert into Table2 (Author) values ('" + txtbxAddA.Text.ToString() + "')";
txtbxAddA.Text = null;
}
if (txtbxAddNP.Text != "")
{
string q = "insert into Table2 (Page Number) values ('" + txtbxAddNP.Text.ToString() + "')";
txtbxAddNP.Text = null;
}
if (txtbxAddP.Text != "")
{
string q = "insert into Table2 (Publisher) values ('" + txtbxAddP.Text.ToString() + "')";
txtbxAddP.Text = null;
}
loaddata();
}
The problem is
you are not executing your query. It is in the string q, but you are not executing it anywhere.
Create a method:
private void UpdateData(query)
{
try
{
cn.Open();
cmd.CommandText = query; //set query to execute
cmd.ExecuteNonQuery(); //executing the query
cn.Close();
}
catch (Exception ex)
{
}
}
Call this method in every if-statement of method btnAdd_Click:
if (txtbxAddT.Text != "")
{
string q = "insert into Table2 (Title) values ('" + txtbxAddT.Text.ToString() + "')";
UpdateData(q);
txtbxAddT.Text = String.Empty; //Set it to "Empty", Null is not Empty
}
//... and so on for every if check
Best practice advice:
Assigning textbox.Text to "" or null is not a good practice.
Use String.Empty instead.
While checking for textbox.Text for being Empty, never use textbox.Text == null or textbox.Text == "", these are also not the best practices and some times create problems.
Use String.IsNullOrEmpty(textbox.Text) instead.

Inserting image in database using mysql with datatype longblob

I Planned to insert image in database. But there is some problem while inserting i.e (image format : input string was not in correct format). Please help me . Thanks in advance.
Error comes in this line -> int count = cmd.ExecuteNonQuery();
I have created the database with img (column name) Blob (datatype).
public partial class check1 : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("server=localhost; database=esample; uid=root;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
protected void btnupload_Click(object sender, EventArgs e)
{
if (fileupload.HasFile)
{
int length = fileupload.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileupload.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
string imagename = imgname.Text;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO brand (imgname,img) VALUES (#imagename,#imagedata)", con);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Blob).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
con.Close();
if(count==1)
{
BindGridData();
imgname.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
private void BindGridData()
{
MySqlConnection con = new MySqlConnection("server=localhost; database=esample; uid=root;");
MySqlCommand command = new MySqlCommand("SELECT imgname,img,bid from brand", con);
MySqlDataAdapter daimages = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}
}
Using a class named Player with the id, name and photo values.
public static bool createUser(Player player)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO tbuser (id,sName,lbFoto) VALUES (#id,#name,#foto)", dbConnection);
cmd.Parameters.AddWithValue("#id", player.id).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("#name", player.Name).DbType = DbType.String;
cmd.Parameters.AddWithValue("#foto", player.Image).DbType = DbType.Binary;
try
{
if (dbConnection.State == ConnectionState.Closed)
dbConnection.Open();
cmd.ExecuteNonQuery();
dbConnection.Close();
return true;
}
}
catch { }
finaly
{
if (dbConnection.State == ConnectionState.Open)
dbConnection.Close();
}
return false;
}
Then for retrieval the data:
public static Player loadUser(string ID)
{
var table = Select(dbConnection, "tbuser", "id = " + ID);
Player player = new Player();
foreach (DataRow row in table.Rows)
{
player.id = (int)row[0];
player.Name = row[1].ToString();
player.Image = (byte[])row[2];
return player;
}
return null;
}
The function Select. This is an extra ;)
public static DataTable Select(MySqlConnection con, string tableName, string expressionWhere)
{
string text = string.Format("SELECT * FROM {0} WHERE {1};", tableName, expressionWhere);
MySqlDataAdapter cmd = new MySqlDataAdapter(text, con);
DataTable table = new DataTable();
if (con.State == ConnectionState.Closed)
con.Open();
try
{
cmd.Fill(table);
}
catch (Exception){}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
return table;
}

Categories