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);
}
}
}
Related
I have a problem with BackgroundWorker! When I get data from Database and try to transfer data to RunWorkerCompleted, I get an error:
System.NullReferenceException The reference to the object does not indicate an instance of the object e was null.
the problem arises in e.Result = dataTable;
private void BackgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
string Refresh = "dbo.GetRenderedService '" + dateTimePicker2.Value.Date.ToString() + "','" + dateTimePicker4.Value.Date.ToString() + "'";
DataTable dataTable = DbConnection.DBConnect(Refresh);
int i = 1;
try
{enter code here
foreach (DataRow dr in dataTable.Rows)
{
backgroundWorker1.ReportProgress(i);
Thread.Sleep(100);
i++;
}
e.Result = dataTable;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void BackgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progBar.Value = e.ProgressPercentage;
}
private void BackgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
source.DataSource = e.Result;
dataGridView1.DataSource = source;
dataGridView1.Columns[0].Visible = false;
dataGridView1.Columns[1].Visible = false;
dataGridView1.Columns[2].Visible = false;
dataGridView1.Columns[3].Visible = false;
dataGridView1.Columns[4].Visible = false;
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[6].Visible = false;
}
This is the class for fetching data from SQL Server.
class DbConnection
{
public static string connectionString = "Data Source=POTITPC-01\\PLMLOCAL;Initial Catalog=Batys;User ID=sa;Password=!sql123;";
public static DataTable DBConnect(string query)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataTable dataTable = new DataTable();
try
{
conn.Open();
da.Fill(dataTable);
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return dataTable;
}
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;
}
}
}
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("تم تعديل السجل بنجاح");
}
}
}
}
For whatever reason the textbox's value does not change when the underlying data does.
Here is what I have thus far:
OdbcConnection dbConnection = new OdbcConnection(connectionString);
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
dbConnection.Open();
PopulateOPCodes();
}
RefreshData(DropDownList1.Items[DropDownList1.SelectedIndex].Text);
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
protected void PopulateOPCodes()
{
var dataReader = new OdbcCommand("SELECT DISTINCT(OP_CD) FROM LDL_FOREMAN", dbConnection).ExecuteReader();
while (dataReader.Read()) DropDownList1.Items.Add(new ListItem(dataReader[0].ToString()));
dbConnection.Close();
}
protected void RefreshData(string OpCode)
{
//var dbCommand = new OdbcCommand("SELECT * FROM LDL_FOREMAN WHERE OP_CD = '" + OpCode + "'", dbConnection);
var dbCommand = new OdbcCommand("SELECT * FROM LDL_FOREMAN WHERE OP_CD = ?", dbConnection);
dbCommand.Parameters.AddWithValue("OP_CD", OpCode);
var dataset = new DataSet();
var dataAdapter = new OdbcDataAdapter(dbCommand);
dataAdapter.Fill(dataset);
GridView1.DataSource = dataset.Tables[0];
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == 5)
{
e.Row.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Linen");
var textBox = new TextBox {Text = e.Row.Cells[1].Text};
e.Row.Cells[1].Controls.Add(textBox);
}
}
I want to display the date which is selected in another form using monthCalender control..
Here is my code..
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
ActivityScheduler frm1 = new ActivityScheduler();
frm1.Show();
}
private void ActivityScheduler_Load(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
RemainderPopUp frm = new RemainderPopUp();
string s = "select * from [Activity_Scheduler]";
SqlCommand sCmd = new SqlCommand(s, con);
SqlDataAdapter da = new SqlDataAdapter(sCmd);
DataSet ds = new DataSet();
da.Fill(ds, "[Activity_Scheduler]");
datagridActivityScheduler.DataSource = ds.Tables[0];
datagridActivityScheduler.AllowUserToAddRows = true;
DataTable dt = new DataTable();
dt = ds.Tables["Activity_Scheduler"];
if (dt == null)
{
datagridActivityScheduler.Rows[0].Cells[3].Value = frm.monthCalendar1.SelectionRange.Start.ToShortDateString();
MessageBox.Show(datagridActivityScheduler.Rows[0].Cells[3].Value.ToString());
}
con.Close();
}
It is displaying the correct value in messagebox..but the value is not displaying in datagridview...
Plz anybody help me out..
Try Following Code :
form_load()
{
private string myDate="1999/12/12";
// Declare a Date property of type string:
public string Name
{
get
{
return myDate;
}
set
{
myName = value;
}
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
ActivityScheduler frm1 = new ActivityScheduler();
ActivityScheduler.myDate = frm.monthCalendar1.SelectionRange.Start.ToShortDateString()
frm1.Show();
}
Now you can get date on other form as :
string myDate = frm1.myDate();
Let me know if any queries.