Null exception with comboBox - c#

I am trying to display data from list of string passed from Main Form into this form but the problem is that I am getting all the time "System.ArgumentNullException" even though the data are correctly passed to the newly declared list. Am I missing something?
public LoginPage()
{
InitializeComponent();
}
WelcomePage secondForm = new WelcomePage();
SqlConnection con;
DataTable dt1 = new DataTable();
public static DataRow dRow2 = null;
public List<string> list = new List<string>();
private void btnSubmit_Click(object sender, EventArgs e)
{
string sql = #"SELECT * FROM [employeeAccount] WHERE [User Name] = #UserName AND [Password] = #Password ";
using (var cmd = new SqlCommand(sql, con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
SqlDataReader reader = cmd.ExecuteReader();
dt1.Load(reader);
ListTransfer();
InputChecker();
con.Close();
}
}
private void LoginPage_Load(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = (#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employeeDatabase.mdf;Integrated Security=True");
}
private void InputChecker()
{
if (dt1.Rows.Count > 0)
{
this.Hide();
secondForm.Closed += (s, args) => this.Close();
secondForm.Show();
}
else
{
MessageBox.Show("Invalid input data!");
}
}
private void ListTransfer()
{
SqlDataAdapter da = new SqlDataAdapter("SELECT [Department] FROM [employeeTable]", con);
DataSet ds = new DataSet();
da.Fill(ds, "employeeTable");
//List<string> list = new List<string>();
foreach(DataRow row in ds.Tables["employeeTable"].Rows)
{
list.Add(row["Department"].ToString());
}
Department_wise_Employee_Details dep = new Department_wise_Employee_Details(list);
}
WelcomePage Form code:
public WelcomePage()
{
InitializeComponent();
}
HomePage thirdForm = new HomePage();
private void btnContinue_Click(object sender, EventArgs e)
{
this.Hide();
thirdForm.Closed += (s, args) => this.Close();
thirdForm.Show();
}
Then it gets to HomePage Form:
List<string> list = new List<string>();
public HomePage()
{
InitializeComponent();
}
public HomePage(List<string>list)
{
InitializeComponent();
this.list = list;
}
private void btn2_Click(object sender, EventArgs e)
{
Department_wise_Employee_Details fourthForm = new Department_wise_Employee_Details(new LoginPage().list);
fourthForm.Show();
}
And from there you get to the form where the data for comboBox I would like to use.

public HomePage()
{
InitializeComponent();
}
List<string> list=new List<string>();
private void ListTransfer()
{
SqlDataAdapter da = new SqlDataAdapter("SELECT [Department] FROM [employeeTable]", con);
DataSet ds = new DataSet();
da.Fill(ds, "employeeTable");
List<string> list = new List<string>();
foreach(DataRow row in ds.Tables["employeeTable"].Rows)
{
list.Add(row["Department"].ToString());
}
// Department_wise_Employee_Details dep = new Department_wise_Employee_Details(list);
}
Department_wise_Employee_Details fourthForm = new Department_wise_Employee_Details(list);
private void btn1_Click(object sender, EventArgs e)
{
fourthForm.Show();
}

From your code snippets it is obvious that dep instance in ListTransfer is never shown. Therefore, the click event where you add the items is from another instance which does not receive the list parameter.

Related

How do I automatically reload the gridview after adding the new name?

I have to automatically reload the gridview which contains the list of the brand names. What should be done to automatically reload the data gridview when the "Brand has been added" meessage is shown.I have the data gridview in another form.
public partial class AddBrand : Form
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
DBConnection dbcon = new DBConnection();
public AddBrand()
{
InitializeComponent();
cn = new SqlConnection(dbcon.MyConnection());
}
private void Clear()
{
btnSave.Enabled = true;
btnUpdate.Enabled = false;
tbBrand.Clear();
tbBrand.Focus();
}
private void BtnSave_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you want to save this brand?", " ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
cn.Open();
cm = new SqlCommand("INSERT INTO tblBrand(brand)VALUES(#brand)", cn);
cm.Parameters.AddWithValue("#brand", tbBrand.Text);
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Brand has been added.");
Clear();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
}
private void btnClose_Click(object sender, EventArgs e)
{
Brand brand = new Brand();
brand.ShowDialog();
}
}
This is the design:
Hope as per your code Brand is the form showing GridView. In this form you can open the form AddBrand.
var addBrand = new AddBrand();
var result = addBrand.ShowDialog();
if(result == DialogResult.Yes)
ReloadLogic()// you can read from db
In BtnSave_Click event in Brand form you can write
this.DialogResult = DialogResult.Yes; Close();
If you want to reload the datagridview when the "Brand has been added" meessage is shown, you can read data to datagridview again.
You can refer to the following code in the form containing datagridview:
private void Form1_Load(object sender, System.EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
DBConnection dbcon = new DBConnection();
cn = new SqlConnection(dbcon.MyConnection());
cn.open();
string sql = "select * from tblBrand";
SqlDataAdapter sda = new SqlDataAdapter(sql, cn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
cn.close();
}

Update/Delete buttons inside DataGridView not working after filtering results

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;
}
}
}

save changes to instance of class reflect changes

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("تم تعديل السجل بنجاح");
}
}
}
}

Display specific Column when checkbox is checked

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);
}
}
}

Display date selected in one form to another form

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.

Categories