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.
Related
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();
}
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;
}
}
}
I have one form with grid(dataGridView1) and textbox(txtSearch). When I type something in textbox grid filter by field acSubject. Now I put second grid and I want new Custom SQL query which will be depend on selected row in dataGridView1.
SQL would be:
select anUserID from the_setsubjcontact where acSubject = #acSubject
How can I do this?
Code is:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=local\s08r2;Initial Catalog=Demo;User id=sa;Password=sa";
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(#"
SELECT acSubject, acAddress, acPost, acName, acPhone,
acFieldSA, acFieldSB, acFieldSC, acFieldSD, acFieldSE,
anFieldNA, anFieldNB, anFieldNC, anFieldND, anFieldNE, OdgovornaOsoba, acSubjTypeBuyer
FROM ARS.dbo._ARSCRM_vSubjekti
", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtSearch.Text))
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
}
else
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("acSubject like '%{0}%'", txtSearch.Text);
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//User selected a cell (show the first cell in the row)
if (dgv.SelectedCells.Count > 0)
txtAcFieldSA.Text = dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[5].Value.ToString();
}
}
I was success when I use DataSet from C#, but with CustomSQL I don't know how to do that.
private void ShowDetails(int UserId)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=local\s08r2;Initial Catalog=Demo;User id=sa;Password=sa";
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(#"
select anUserID from the_setsubjcontact where acSubject = #acSubjec", con);
da.SelectCommand.Parameters.AddWithValue(#acSubjec, UserId.ToString());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//User selected a cell (show the first cell in the row)
if (dgv.SelectedCells.Count > 0 && dgv.SelectedCells[0].RowIndex >-1 && dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells.Count > 0)
txtAcFieldSA.Text = dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[0].Value.ToString();
ShowDetails(int.Parse(txtAcFieldSA.Text));
}
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.
I want to populate TWO dropdownlist, based on selection of first dropdownlist the second dropdownlist will get populated.
Example :
Like i have two dropdownlist namely 1.ddlCountry and 2.ddlState
Now when country is selected then depending on the selected Country the States related with that Country will get populated in the State dropdownlist. I want to achieve this withour reloading the whole page in Asp.Net with coding language as C#.
How can i achieve the same?
Dropdownlist is fetching data from database by executing query.
You can use AJAX toolkit CascadingDropDown as told by Naresh.
OR
use ajax update panel and keep all Dropdowns in it. So the whole page will not load on changing dropdown value.
You didnt give the code to further solution.
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
FillStateByCountry();
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
FillLocationByCountryandState();
}
private void FillStateByCountry()
{
DataSet dstFillState;
int CountryId = Convert.ToInt32(ddlCountry.SelectedValue.ToString());
dstFillState = Tbl_State.FillDDLState(CountryId);
ddlState.DataSource = dstFillState;
ddlState.DataTextField = "State";
ddlState.DataValueField = "Id";
ddlState.DataBind();
}
similarly FillLocationByCountryandState();
Add two dropdownlists to your form and name it as cmbStates, cmbCities
when you select state name from cmbStates(dropwdownlist), cmbCities(dropdownlist) generates cities based on state name(cmbStates)
by fetching data from database
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=pbs-server;database=p2p;user id=shekar;password=sekhar#1346");
SqlCommand cmd = new SqlCommand("select states from Country", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "Country");
cmbStates.DataSource = ds.Tables[0];
cmbStates.SelectedValue = 0;
con.Close();
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=xxxx;database=xxxx;user id=xxxxr;password=xxxxxx");
SqlCommand cmd = new SqlCommand("select cities from States where cityname = 'cmbStates.SelectedItem.ToString()'", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "States");
cmbCities.DataSource = ds.Tables[0];
cmbCities.SelectedValue = 0;
con.Close();
}
OR
manually adding items
namespace DropDownlist
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmbStates.Items.Add("Andhra Pradesh");
cmbStates.Items.Add("Tamilnadu");
cmbStates.Items.Add("Karnataka");
cmbStates.SelectedValue = 0;
}
private void cmbStates_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbStates.SelectedItem.ToString() == "Andhra Pradesh")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Hyderabad");
cmbCities.Items.Add("Guntur");
cmbCities.Items.Add("Vijayawada");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Tamilnadu")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Chennai");
cmbCities.Items.Add("Coimbatore");
cmbCities.Items.Add("ooty");
cmbCities.SelectedValue = 0;
}
else if (cmbStates.SelectedItem.ToString() == "Karnataka")
{
cmbCities.Items.Clear();
cmbCities.Items.Add("Bangalore");
cmbCities.Items.Add("Mangalore");
cmbCities.SelectedValue = 0;
}
else
{
MessageBox.Show("Please Select any value");
}
}
}
}