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

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

Related

label does not behave properly

I am devleoping a online airline reservation system in which i have two dropdownlists to select source and destinations and a label .this label will show " there are no flights" if there are no matching routes retrieved from the database (in this case its sqlserver 2008).i have written the following code which tries to do so, but when i postback or refresh the page the label with " there are no flights" is till visible.what is wrong with my code please anyone help me with that.
public partial class Dropdndemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con=new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
//string Sqlcmnd="select Source from Ars2.1.2.dbo.Scheduling";
con.Open();
if (!Page.IsPostBack)
{
SqlCommand com = new SqlCommand("select distinct Source from Schedulings", con);
SqlCommand comn=new SqlCommand("select distinct Destination from Schedulings", con);
//SqlDataReader readr;
DropDownList1.DataSource = com.ExecuteReader();
DropDownList1.DataTextField = "Source";
// DropDownList1.DataTextField = "Destination";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "select Source");
con.Close();
con.Open();
DropDownList2.DataSource = comn.ExecuteReader();
DropDownList2.DataTextField = "Destination";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, "select Destination");
con.Close();
}
//con.Close();
// DropDownList1.DataBind();
//con.Close();
if (IsPostBack)
Label3.Text = "";
//Label1.Visible = false;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// string Source = DropDownList1.SelectedValue.ToString();
// Label1.Text = Source;
}
protected void Button1_Click(object sender, EventArgs e)
{
string src = DropDownList1.SelectedItem.ToString();
string desti = DropDownList2.SelectedItem.ToString();
if ((src == desti) && IsPostBack)
{
Label1.Text = "Source And Destination cant be same!";
}
SqlConnection lop = new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
lop.Open();
SqlCommand cmd = new SqlCommand("select * from Schedulings where Source=#Source and Destination=#Destination", lop);
cmd.Parameters.AddWithValue("Source", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("Destination", DropDownList2.SelectedItem.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 0)
{
Label3.Text = "No planes available in this route!!!";
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
I suppose you are refreshing page using F5 or by right clicking on page and opting refresh option or using refresh button of browser. If this is the case then I am scared it's not refresh, it's repeating previous action. That means if you were searching for flight and refreshing using above options, it will again search for flight using same search criteria. You can confirm it by putting debugger on search event. You can avoid this behavior by setting and clearing Session or ViewState and manage label text using it.

Update not working from grid view (not able to get the error )

I'm trying to update a table from the gridview of tool to the SQL database. The problem is it's not getting updated in the database.
Below is my code for the button click which updates the database:
while debugging the code i found that the data table DT is fetching only the source values not the updated one in the grid view....
Is there any property in the grid view which accepts these change and updates the DT table ?
public partial class BusinessRules : Form
{
//Declaration Part
private SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AnimalProductsCoSD;Integrated Security=True");
private string sqlconn; // query and sql connection
private SqlDataAdapter SDA = new SqlDataAdapter();
DataTable DT = new DataTable();
SqlCommandBuilder scb = new SqlCommandBuilder();
private void button_retreive_Click(object sender, EventArgs e)
{
string commandText = "CoSD.RetreiveBusinessRulesTool";
SqlCommand cmd = new SqlCommand(commandText, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#BusinessType", SqlDbType.NVarChar, 60).Value = comboBox_BusinessType.Text;
cmd.Parameters.Add("#CommodityGroup", SqlDbType.VarChar, 60).Value = comboBox_group.Text;
try
{
con.Open();
SDA.SelectCommand = cmd;
DT = new DataTable();
SDA.Fill(DT);
int count1 = DT.Rows.Count;
if (DT.Rows.Count > 0)
{
dataGridView.DataSource = DT;
dataGridView.Columns[0].DefaultCellStyle.ForeColor = Color.Gray;
dataGridView.Columns[0].ReadOnly = true;
}
else
{
MessageBox.Show("No Business Rules Found");
}
}
catch (SqlException ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
}
private void button_update_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
scb = new SqlCommandBuilder(SDA);
SDA.Update(DT);
// confirm
MessageBox.Show("Updates successfully submitted to CoSD");
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
In the try, put this
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
In your initializer call
SqlDataAdapter sda= new SqlDataAdapter("SELECT * FROM someWhere", connectionString);
DataTable dt = new DataTable();
The problem is that you refresh the datagridview before submitting the changes, thus deleting anything inputted
**** EDIT ****
This is exactly what my code in a project I did a little while back looks like:
namespace TowerSearch
{
public partial class EditParts : Form
{
const string conString = ConString.conString;
static DataClasses1DataContext PartsLog = new DataClasses1DataContext(conString);
static Table<Part> listOfParts = PartsLog.GetTable<Part>();
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public EditParts()
{
InitializeComponent();
}
//Load and refresh the dataGridView
private void showData()
{
SqlConnection con = new SqlConnection(conString);
sda = new SqlDataAdapter("SELECT * FROM Parts", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void EditParts_Load(object sender, EventArgs e)
{
showData();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
dataGridView1.Refresh();
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
MessageBox.Show("Saved");
showData();
}
catch (Exception ee)
{
MessageBox.Show("There is an error in the data!\nCheck if there are any blank spots besides Quantity.");
}
}
}
}
That definitely works, so try the code with the show data. I'd suggest just copying it verbatim first to see if it would work.
**** EDIT 2 ****
Another thing that you could try if you haven't managed to get it already is add a bindingSource. To do this, drag a bindingSource onto your dataGridView and then set the DataSource option to the table of the DB that you wan't to display
Hope that helps!

How to copy, paste and insert data in datagridview

I'm new to visual studio c# (2015) and learning it online. It is bit confusing a bit because of different ways it's being showed.
What I'm trying to accomplish is this: The result set is showed after the I hit enter; I want to be able to copy a selected row or copy the whole result set and paste it.
Also, would like to add new rows. It's currently running and able to update the records.
Please see below code:
namespace Offerlist
{
public partial class frmMain : Form
{
DataSet ds = new DataSet();
SqlConnection cs = new SqlConnection("data source = TLKCDDB05;" +
" initial catalog=cabledb; integrated security=TRUE");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cmd = new SqlCommandBuilder();
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnEnter_Click(object sender, EventArgs e)
{
da.SelectCommand = new SqlCommand
("select * from mc_client_offerlist where campcode like'" +
"%" + txtCampCode.Text + "' and offertype>0 order by crc ASC", cs);
ds.Clear();
da.Fill(ds);
dg.DataSource = ds.Tables[0];
}
private void txtCampCode_TextChanged(object sender, EventArgs e)
{
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
cmd = new SqlCommandBuilder(da);
da.Update(ds);
MessageBox.Show("Updated", "Update",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

Null exception with comboBox

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.

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