I`m using this code to read from a sqlite table and add the row where it is to the DataGridview. The problem is that if I want to add the same item more than once, it will only add once. I want to be able to add as many items as I want.
private SQLiteConnection sql_con;
private SQLiteCommand sql_cmd;
private SQLiteDataAdapter DB;
private DataSet DS = new DataSet();
private DataTable DT = new DataTable();
private void btnAdicionaProduto_Click(object sender, EventArgs e)
{
string cmdInsereProdutos = "select codigo,Nome,Unidade,Valor from Produtos where codigo = #codigo";
InsereProdutosCaixa(cmdInsereProdutos);
if (dataGridViewProdutos.RowCount > 0)
{
dataGridViewProdutos.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewProdutos.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridViewProdutos.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewProdutos.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
for (int i = 0; i < dataGridViewProdutos.Columns.Count; i++)
{
int colw = dataGridViewProdutos.Columns[i].Width;
dataGridViewProdutos.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
dataGridViewProdutos.Columns[i].Width = colw;
}
txtCodigo.Text = "";
txtCodigo.Focus();
}
}
private void InsereProdutosCaixa(string txtQuery)
{
try
{
SetConnection();
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
sql_cmd.Parameters.AddWithValue("#codigo", txtCodigo.Text);
sql_cmd.CommandText = txtQuery;
SQLiteDataReader readerProduto = sql_cmd.ExecuteReader();
DT.Load(readerProduto);
dataGridViewProdutos.DataSource = DT;
sql_con.Close();
}
catch (SQLiteException e)
{
MessageBox.Show(e.ToString(), "ERRO");
}
}
Related
C# winform application: i added buttons in datagridview in every row for (update,delete). it works fine but when i search data in this gridview the buttons doesn't work on search results.
Here is my code.
namespace MyBusiness
{
public partial class ExpenceDetails : Form
{
public ExpenceDetails()
{
InitializeComponent();
}
private void ExpenceDetails_Load(object sender, EventArgs e)
{
update();
}
DataTable data;
public void update()
{
string connectionstring = null;
SqlConnection cnn;
connectionstring = #"Server=(local)\SQLEXPRESS;Database=mrtraders;Trusted_Connection=True";
cnn = new SqlConnection(connectionstring);
try
{
cnn.Open();
dataGridView1.ColumnCount = 0;
SqlCommand cmd1 = new SqlCommand("SELECT * FROM Expense", cnn);
SqlDataReader reader = cmd1.ExecuteReader();
if (reader.HasRows)
{
data = new DataTable();
data.Load(reader);
dataGridView1.DataSource = data;
}
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.Text = "Update";
btn.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(btn);
DataGridViewButtonColumn btn2 = new DataGridViewButtonColumn();
btn2.Text = "Delete";
btn2.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(btn2);
cnn.Close();
}
catch (Exception)
{
myMessageBox my = new myMessageBox("Internal Error...");
my.ShowDialog();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 4)
{
if (e.RowIndex >= 0)
{
//// get ExpenseId//// IMP
int id = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
string desc = Convert.ToString(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value);
int am = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[3].Value);
UpdateExpense a = new UpdateExpense(id,desc,am);
a.ShowDialog();
dataGridView1.DataSource = null;
update();
}
}
else if (e.ColumnIndex == 5)
{
if(e.RowIndex >= 0)
{
int id = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
string connectionstring = null;
SqlConnection cnn;
connectionstring = #"Server=(local)\SQLEXPRESS;Database=mrtraders;Trusted_Connection=True";
cnn = new SqlConnection(connectionstring);
try
{
cnn.Open();
SqlCommand cmd1 = new SqlCommand("Delete FROM Expense where expenseId = '"+id+"' ", cnn);
cmd1.ExecuteNonQuery();
myMessageBox my = new myMessageBox("Deleted Successfully...");
my.ShowDialog();
dataGridView1.DataSource = null;
cnn.Close();
update();
}
catch (Exception)
{
myMessageBox my = new myMessageBox("Internal Error...");
my.ShowDialog();
}
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(data);
dv.RowFilter = string.Format("Description like '%{0}%'", textBox1.Text);
dataGridView1.DataSource = dv.Table;
}
}
}
Retrieving data from sqldatabase in gridview using background worker. Skips already added data and added an extra data of same type, using breakpoint or message-box it displays correct data, but not in datagridview! Anyone can point out where is the mistake in the below code? Any help is appreciated
private void button8_Click(object sender, EventArgs e)
{
//gridviewMain();
toolStripStatusLabel1.Visible = true;
progressBar1.Maximum = GetTotalRecords();
progressBar1.Visible = true;
dataGridView1.ColumnCount = 9;
dataGridView1.Columns[0].Name = "Accession No";
dataGridView1.Columns[1].Name = "Author";
dataGridView1.Columns[2].Name = "Title";
dataGridView1.Columns[3].Name = "Edition";
dataGridView1.Columns[4].Name = "ClassNo";
dataGridView1.Columns[5].Name = "BookNo";
dataGridView1.Columns[6].Name = "Subject";
dataGridView1.Columns[7].Name = "Department";
dataGridView1.Columns[8].Name = "Status";
dataGridView1.Columns[8].Visible = false;
if (!bgwFillDGV.IsBusy)
{
RetriveTableData TObj = new RetriveTableData();
dataGridView1.Rows.Clear();
bgwFillDGV.RunWorkerAsync(TObj);
}
}
private int GetTotalRecords()
{
SqlConnection con;
SqlCommand cmd;
try
{
using (con = new SqlConnection(connectionString))
{
cmd = new SqlCommand("SELECT COUNT(*) FROM tblBook", con);
con.Open();
TotalRecords = int.Parse(cmd.ExecuteScalar().ToString());
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return TotalRecords;
}
public class RetriveTableData
{
public string AccessionNo;
public string Author;
public string Title;
public string Edition;
public string ClassNo;
public string BookNo;
public string Subject;
public string Department;
public string Status;
}
private void bgwFillDGV_DoWork(object sender, DoWorkEventArgs e)
{
RetriveTableData Obj = (RetriveTableData)e.Argument;
string SqlcmdString = "SELECT * from tblBook";
SqlDataReader reader;
int i = 1;
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
Sqlcmd = new SqlCommand(SqlcmdString, conn);
conn.Open();
reader = Sqlcmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//int.Parse(reader["NO_IND"].ToString());
Obj.AccessionNo = reader["accessionNo"].ToString();
Obj.Author = reader["author"].ToString();
Obj.Title = reader["title"].ToString();
Obj.Edition = reader["edition"].ToString();
Obj.ClassNo = reader["classNo"].ToString();
Obj.BookNo = reader["bookNo"].ToString();
Obj.Subject = reader["subject"].ToString();
Obj.Department = reader["department"].ToString();
Obj.Status = reader["status"].ToString();
System.Threading.Thread.Sleep(100);
// To Report progress.0
MessageBox.Show(Obj.AccessionNo.ToString());
bgwFillDGV.ReportProgress(i, Obj);
if (bgwFillDGV.CancellationPending)
{
// Set the e.Cancel flag so that the WorkerCompleted event
// knows that the process was cancelled.
e.Cancel = true;
bgwFillDGV.ReportProgress(0);
return;
}
i++;
}
conn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void bgwFillDGV_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
if (!bgwFillDGV.CancellationPending)
{
RetriveTableData Obj = (RetriveTableData)e.UserState;
dataGridView1.Rows.Add(Obj.AccessionNo.ToString(), Obj.Author.ToString(), Obj.Title.ToString(), Obj.Edition.ToString(), Obj.ClassNo.ToString(), Obj.BookNo.ToString(), Obj.Subject.ToString(), Obj.Department.ToString(),Obj.Status.ToString());
progressBar1.Value = e.ProgressPercentage;
toolStripStatusLabel1.Text = "Processing row.. " + e.ProgressPercentage.ToString() + " of " + TotalRecords;
}
}
private DataTable objToDataTable(RetriveTableData obj)
{
RetriveTableData objmkt = new RetriveTableData();
sTable3.Columns.Add("AccessionNo",typeof(string));
sTable3.Columns.Add("Author", typeof(string));
sTable3.Columns.Add("Title", typeof(string));
sTable3.Columns.Add("Edition", typeof(string));
sTable3.Columns.Add("ClassNo", typeof(string));
sTable3.Columns.Add("BookNo", typeof(string));
sTable3.Columns.Add("Subject", typeof(string));
sTable3.Columns.Add("Department", typeof(string));
sTable3.Columns.Add("Status", typeof(string));
foreach (PropertyInfo info in
typeof(RetriveTableData).GetProperties())
{
sTable3.Rows.Add(info.Name);
}
sTable3.AcceptChanges();
return sTable3;
}
friends i'm using class and ado.net
i'm using data table connection oledb and so on
when I take instance of this class using form load to load data on a form control like text box and combo and so on
i do some operation using this instance like add record delete record edit record
i have also navigation button move2first move2last and so on
what is my problem:
my problem when do insert delete update on this instance of class this changes not reflect on the instance it self
when moving using button move i see the same record
how to update the instance of class to reflect the changes
this is class
class dataConnection
{
public int affectedrecord;
//Microsoft.Jet.OLEDB.4.0
public OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Properties.Settings.Default.dPath + ";Jet OLEDB:Database Password=azouz(2016)");
OleDbDataAdapter da;
DataTable dt =new DataTable() ;
OleDbCommand com;
int intRow = 0;
DataRow r;
public DataTable loadingdata(string sql)
{
dt.Clear();
da = new OleDbDataAdapter(sql, cn);
da.Fill(dt);
return dt;
}
public void saverecord(string sql,string[]para,string[]val)
{
cn.Open();
com = new OleDbCommand();
com.CommandText = sql;
com.Connection = cn;
com.CommandType = CommandType.Text;
for (int i = 0; i< para.Count(); i++)
{
com.Parameters.AddWithValue(para[i], val[i]);
}
affectedrecord = com.ExecuteNonQuery();
if (affectedrecord > 0)
{
affectedrecord = 1;
}
cn.Close();
}
public void EditRecord(string sql, string [] para,string []val)
{
cn.Open();
com = new OleDbCommand();
com.CommandText = sql;
com.Connection = cn;
com.CommandType = CommandType.Text;
int x = para.Count();
for (int i = 0; i < para.Count(); i++)
{
com.Parameters.AddWithValue(para[i], val[i]);
}
affectedrecord = com.ExecuteNonQuery();
if (affectedrecord > 0)
{
affectedrecord = 1;
}
cn.Close();
}
public void DeleteRecord(string sql,string [] para,string []val)
{
cn.Open();
com = new OleDbCommand();
com.CommandText = sql;
com.Connection = cn;
com.CommandType = CommandType.Text;
for (int i =0;i<1;i++)
{
com.Parameters.AddWithValue(para[i], val[i]);
}
affectedrecord = com.ExecuteNonQuery();
if (affectedrecord > 0)
{
affectedrecord = 1;
}
cn.Close();
}
operation on form
public partial class frmRegStore : Window
{
public frmRegStore()
{
InitializeComponent();
}
#region Variables
// 'هذا النموذج يعتمد علي
//' class
//' c worktable
//'لملئ النموذج وورقة البيانات بالسجلات
//'تعريف كائن من الكلاس
dataConnection TotalWork = new dataConnection();
DataTable dt = new DataTable();
DataRow r;
#endregion
private void btnSave_Click(object sender, RoutedEventArgs e)
{
string[] para = { "#storeName" };
string[] val = { this.txtStoreName.Text };
dataConnection Stores = new dataConnection();
Stores.saverecord("insert into Stores (StoreName)values(?);", para, val);
if (Stores.affectedrecord > 0)
{
MessageBox.Show("تم اضافة السجل بنجاح");
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
dt = TotalWork.loadingdata("Select * from Stores");
r = TotalWork.Move2First();
showData();
}
public void showData()
{
if ((r != null))
{
this.txtStoreID.Text = r[0].ToString();
this.txtStoreName.Text = r[1].ToString();
}
}
private void btnLast_Click(object sender, RoutedEventArgs e)
{
r = TotalWork.Move2Last();
showData();
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
r = TotalWork.Move2Next();
showData();
}
private void btnPrevious_Click(object sender, RoutedEventArgs e)
{
r = TotalWork.Move2Previous();
showData();
}
private void btnFirst_Click(object sender, RoutedEventArgs e)
{
r = TotalWork.Move2First();
showData();
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
string[] para = { "#storeID" };
string[] val = { this.txtStoreID.Text };
dataConnection Stores = new dataConnection();
Stores.saverecord("Delete from Stores where StoreId =?", para, val);
if (Stores.affectedrecord > 0)
{
MessageBox.Show("تم حذف السجل بنجاح");
}
}
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
string[] para = {"#storeName", "#storeID" };
string[] val = { this.txtStoreName.Text,this.txtStoreID.Text };
dataConnection Stores = new dataConnection();
Stores.saverecord("update Stores set StoreName = #storeName where StoreId =#storeID", para, val);
if (Stores.affectedrecord > 0)
{
MessageBox.Show("تم تعديل السجل بنجاح");
}
}
}
}
I would like to display a specific column (date of birth, for an example) on a dataGridView which is connected to MS Access, when a checkbox (date of birth checkbox) is checked. It would help much more if it was an array, because I want to add more than one checkbox.
namespace emp_db1
{
public partial class Print : Form
{
private OleDbConnection connection = new OleDbConnection();
public Print()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = emp_0.mdb";
}
DataTable ds;
private void Print_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT ID, Name, DOB FROM emp_per";
OleDbDataAdapter da = new OleDbDataAdapter(command);
ds = new DataTable();
da.Fill(ds);
dataGridView1.DataSource = ds;
da.Update(ds);
connection.Close();
dataGridView1.AutoResizeColumns();
dataGridView1.AutoResizeColumnHeadersHeight();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
this.dataGridView1.Sort(this.dataGridView1.Columns[0], ListSortDirection.Ascending);
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dob_check_CheckedChanged(object sender, EventArgs e)
{
}
}
}
thankyou.
Solution :
namespace emp_db1
{
public partial class Print : Form
{
List<CheckBox> chkboxes = new List<CheckBox>();
private OleDbConnection connection = new OleDbConnection();
public Print()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = emp_0.mdb";
}
DataTable ds;
private void Print_Load(object sender, EventArgs e)
{
chkboxes.Add(dob_check); //0
chkboxes.Add(mother_check); //1
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT ID, Name, DOB, Mother FROM emp_per";
OleDbDataAdapter da = new OleDbDataAdapter(command);
ds = new DataTable();
da.Fill(ds);
dataGridView1.DataSource = ds;
da.Update(ds);
connection.Close();
dataGridView1.AutoResizeColumns();
dataGridView1.AutoResizeColumnHeadersHeight();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
this.dataGridView1.Sort(this.dataGridView1.Columns[0], ListSortDirection.Ascending);
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void refreshCheckBoxes(int id)
{
for(int x = 0; x < 2; x++)
{
if (!chkboxes[x].Checked) dataGridView1.Columns[x+2].Visible = false; else dataGridView1.Columns[x+2].Visible = true;
}
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
}
private void dob_check_CheckedChanged(object sender, EventArgs e)
{
refreshCheckBoxes(0);
}
private void mother_check_CheckedChanged(object sender, EventArgs e)
{
refreshCheckBoxes(1);
}
}
}
I have a datagrid view and it's datasource is MS Access(which have a datatype, currency, date/time, and numbers), It shows data in the database but doesn't show other data types, only words or any string, here is my code for adding rows
string[] rowData = new string[columnCount];
while (dr.Read())
{
for (int k = 0; k < columnCount; k++)
{
if (dr.GetFieldType(k).ToString() == "System.int32")
{
rowData[k] = dr.GetInt32(k).ToString();
}
if (dr.GetFieldType(k).ToString() == "System.String")
{
rowData[k] = dr.GetString(k);
}
}
dataGridView1.Rows.Add(rowData);
}
can you help me with this? thanks
Instead of using the code above, I use this code, and it works
private void Form6_Load(object sender, EventArgs e)
{
loadData();
}
private void loadData()
{
str = new OleDbConnectionStringBuilder();
str.Provider = "Microsoft.ace.Oledb.12.0";
str.DataSource = #"\\sisc-erelim\4_Printing\VTDB\DB\VirginiTEADB2.accdb";
con = new OleDbConnection(str.ConnectionString);
dataGridView1.DataSource = fillTable("Select* from Accountstbl");
dataGridView1.Columns["Password"].Visible = false;
dataGridView1.Columns["Picture"].Visible = false;
}
private DataTable fillTable(string sql)
{
DataTable datatable = new DataTable();
using (OleDbDataAdapter da = new OleDbDataAdapter(sql, con))
{
da.Fill(datatable);
}
return datatable;
}