I got my form "InsertClient" and I have the button click method
public void Insert_Button_Click(object sender, EventArgs e)
{
MyClass.InsertNewClient(fullNametxt.Text, shortNametxt.Text);
fullNametxt.Clear();
shortNametxt.Clear();
fullNametxt.Focus();
GridView.Update();
GridView.Refresh();
}
My class recieve this:
public static void InsertNewClient (String fullName, String shortName)
{
SqlConnection conn = DBClass.ConnectionString.GetConnection();
SqlCommand cmd = new SqlCommand("MyStoredProcedure", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#fullName", fullName);
cmd.Parameters.AddWithValue("#shortName", shortName);
int i = cmd.ExecuteNonQuery();
if (i == 0)
{
MessageBox.Show("Can't save data");
}
if (i > 0)
{
MessageBox.Show("Data saved!");
}
}
The thing is, the data is saved but that the DataGridView does not refresh after each INSERT (button click). I have to close the form and re-open it and appears refreshed.
Please help, I want the DataGridView refresh after INSERT data
cCUSTOMERBindingSource Is the object of my BindingSource generated using ToolBox.
public void ReloadGrid()
{
Cursor.Current = Cursors.WaitCursor;
cCUSTOMERBindingSource.DataSource = bd.C_CUSTOMER.ToList();
Cursor.Current = Cursors.Default;
}
this where I called the method
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
C_CUSTOMER cst = new C_CUSTOMER();
C_ACCOUNT acc = new C_ACCOUNT();
cst.FIRST_NAME = txtFname.Text;
cst.MIDDLE_NAME = txtMname.Text;
cst.LAST_NAME = txtLname.Text;
cst.LOCATION = txtlocation.Text;
cst.DATE_OF_BIRTH = Convert.ToDateTime(dateTimePicker1.Text);
acc.ACCOUNT_BALANCE = Convert.ToInt32(txtInitAmoun.Text);
acc.ACCOUNT_NUMBER = Convert.ToInt32(txtAccNumber.Text);
cst.TELEPHONE = Convert.ToInt32(txtTelephone.Text);
cst.DATE_CREATE = DateTime.Now;
int newID = cstDao.insertCustomer(cst.FIRST_NAME, cst.MIDDLE_NAME, cst.LAST_NAME, cst.LOCATION, cst.DATE_OF_BIRTH, cst.TELEPHONE, cst.MODIFY_BY, cst.DATE_MODIFY, cst.DATE_CREATE);
acc.CUSTOMER_ID = newID;
acc.DATE_CREATED = DateTime.Now;
acc.CREATED_BY = 1;
int newAccID = cstDao.insertAccount(acc);
if(newID != 0 && newAccID != 0) {
MessageBox.Show("Insert Succefull", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Error during the insertion", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ReloadGrid();
}
On Form load
private void Form3_Load(object sender, EventArgs e)
{
bd = new Customer_DBEntities();
cCUSTOMERBindingSource.DataSource = bd.C_CUSTOMER.ToList();
}
You should have separate method for example Refresh() which in your case will obtain data from sql using sqlDataReader and after your insertBtn call that method and initialize dataGridView DataSource to it
Something like that #mmking, but not exactly
I already solved it.. the problem was exactly what #Fabio said...
Inside of the button click method I fill again de DataGridView with the DataSet.
public void Insert_Button_Click(object sender, EventArgs e)
{
MyClass.InsertNewClient(fullNametxt.Text, shortNametxt.Text);
this.tblClientTableAdapter.Fill(this.DataSetClient.tblClient);
}
Just to get clear... I use the DataGridView of toolbox, select "Choose data source" and select the table that I want to use to fill DataGrid...
I use the DataSetName that gave me by default and put it right like I show it in the code
Hope it helps for future questions
Related
I m working on a shopping cart like Form in WF. I have a DataGridView an ADD_Button and Submit_Button.The user will choose Items From inventory and Click ADD_ButtonThe item will go into DataGridView After Finishing User will click Submit_Button then detail will go into DB.
Question: is this After adding a product/row into DatagridView When I add same product again.it goes into the new row I want that Where Pro_ID Column Match, The row update with new qty. I tried to search the web but all I got SQL queries.
private void btn_Add_Click(object sender, EventArgs e)
{
i = dgv_Purchase.Rows.Count;
try
{
dgv_Purchase.Rows.Add();
.......
.......
dgv_Purchase.Rows[i - 1].Cells["Pro_ID"].Value = txt_ProID.Text;
.......
.......
dgv_Purchase.Rows[i - 1].Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
catch (Exception ){}
}
This is Submit Button Code
private void btnInsert_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["PRMSConnectionString"].ToString();
SqlConnection con = new SqlConnection(cs);
SqlTransaction objTransaction;
for (int i = 0; i < dgv_Purchase.Rows.Count - 1; i++)
{
//SomeCode part of code
SqlCommand objCmd2;
string cmd2 = "INSERT INTO PurchaseMaster " +
" (Pro_ID , category_ID, Purchase_Qty) " +
"VALUES (#Pro_ID, #category_ID, #Purchase_Qty)";
objCmd2 = new SqlCommand(cmd2, con, objTransaction);
objCmd2.Parameters.AddWithValue("#Pro_ID_ID", dgv_Purchase.Rows[i].Cells["Pro_ID"].Value.ToString());
objCmd2.Parameters.AddWithValue("#Category_ID", dgv_Purchase.Rows[i].Cells["Category_ID"].Value.ToString());
objCmd2.Parameters.AddWithValue("#Purchase_Qty", Convert.ToInt32(dgv_Purchase.Rows[i].Cells["Purchase_Qty"].Value.ToString()));
objCmd2.Parameters.AddWithValue("#Date_Today", Convert.ToDateTime(dgv_Purchase.Rows[i].Cells["Purchase_Date"].Value.ToString()));
...........................
Rest of the Code
...........................
try
{
objCmd2.ExecuteNonQuery();
objTransaction.Commit();
}
catch (Exception) {}
}
}
Try this:
private void AddInfo()
{
// flag so we know if there was one dupe
bool updated = false;
// go through every row
foreach (DataGridViewRow row in dgv_Purchase.Rows)
{
// check if there already is a row with the same id
if (row.Cells["Pro_ID"].ToString() == txt_ProID.Text)
{
// update your row
row.Cells["Purchase_Qty"] = txt_Qty.Text;
updated = true;
break; // no need to go any further
}
}
// if not found, so it's a new one
if (!updated)
{
int index = dgv_Purchase.Rows.Add();
dgv_Purchase.Rows[index].Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
}
I edit it with a DGVrow instead of DataRow
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
if (dr.Cells["Pro_ID"].Value.ToString() == txt_ProID.Text)
{
dr.Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
}
I am having a difficult time pinpointing what am I doing wrong here. My logic is to run the stored procedure (UpdateRate) only if a textbox changes. If there is no change in the textbox, just skip the stored procedure for that row of information and move to the next one.
Can someone please help me figure this out? I have tried everything. Keep in mind that I am new at this and might not fully understand complicated answers.
C#:
public partial class MainWindow :
{
internal static string oldAvgRate;
internal static string oldOTRate;
internal static string ratetype;
internal static string rtOT;
public MainWindow()
{
InitializeComponent();
string connectionString = "datasource=;port=;username=;password=";
string sDate = DateTime.Now.ToString("yyyy-MM-dd");
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand avgRate = new MySqlCommand("Select ID, DateFrom, DateTo, RateType, Amount, Description from Daily.Rates where RateType = 'Average Hourly Wages' and DateTo >= #sDate", connection);
avgRate.Parameters.Add(new MySqlParameter("sDate", sDate));
MySqlCommand otRate = new MySqlCommand("Select ID, DateFrom, DateTo, RateType, Amount, Description from Daily.Rates where RateType = 'Average OT Hourly Wages' and DateTo >= #sDate", connection);
otRate.Parameters.Add(new MySqlParameter("sDate", sDate));
try
{
connection.Open();
MySqlDataReader AvgR = avgRate.ExecuteReader();
while (AvgR.Read())
{
txtAHW.Text = AvgR["Amount"].ToString();
dfAHW.Text = AvgR["DateFrom"].ToString();
dtAHW.Text = AvgR["DateTo"].ToString();
txtcommAHW.Text = AvgR["Description"].ToString();
oldAvgRate = txtAHW.Text = AvgR["Amount"].ToString();
ratetype = AvgR["RateType"].ToString();
}
AvgR.Close();
AvgR.Dispose();
MySqlDataReader OtR = otRate.ExecuteReader();
while (OtR.Read())
{
txtOTHW.Text = OtR["Amount"].ToString();
dfOTHW.Text = OtR["DateFrom"].ToString();
dtOTHW.Text = OtR["DateTo"].ToString();
txtcommOTHW.Text = OtR["Description"].ToString();
oldOTRate = txtOTHW.Text = OtR["Amount"].ToString();
rtOT = OtR["RateType"].ToString();
}
OtR.Close();
OtR.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
private string UpdateRate(string dateFrom, string newRate, string oldRate, string ratetype, string description)
{
string connectionString = "datasource=;port=;Initial Catalog='';username=;password=";
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
connection.Open();
MySqlCommand cmd = new MySqlCommand("UpdateRate", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p_DateFrom", MySqlDbType.Date).Value = dateFrom;
cmd.Parameters.Add("#p_NewAmount", MySqlDbType.Decimal).Value = newRate;
cmd.Parameters.Add("#p_OldAmount", MySqlDbType.Decimal).Value = oldRate;
cmd.Parameters.Add("#p_RateType", MySqlDbType.VarChar).Value = ratetype;
cmd.Parameters.Add("#p_Description", MySqlDbType.VarChar).Value = description;
cmd.ExecuteNonQuery();
connection.Close();
return newRate;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
private bool txtAHWHasChangedFlag;
private bool txtOTHWHasChangedFlag;
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
var control = sender as TextBox;
if (control.Name == "txtAHW" )
txtAHWHasChangedFlag = true;
else if (control.Name == "txtOTHW")
txtOTHWHasChangedFlag = true;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAHWHasChangedFlag) //True regardless if changes are made in the textbox or not :(
{
oldAvgRate = UpdateRate(dfAHW.SelectedDate.Value.ToString("yyyy-MM-dd"), txtAHW.Text, oldAvgRate, ratetype, txtcommAHW.Text);
MessageBox.Show("Done", "Test", MessageBoxButton.OK);
}
if (txtOTHWHasChangedFlag) //True regardless if changes are made in the textbox or not :(
{
oldOTRate = UpdateRate(dfOTHW.SelectedDate.Value.ToString("yyyy-MM-dd"), txtOTHW.Text, oldOTRate, rtOT, txtcommOTHW.Text);
MessageBox.Show("Done", "Test", MessageBoxButton.OK);
}
if (!txtAHWHasChangedFlag && !txtOTHWHasChangedFlag)
{
MessageBox.Show("Nothing has changed", "Test", MessageBoxButton.OK);
return;
}
}
}
XAML:
<TextBox x:Name="txtAHW" TextChanged="textChangedEventHandler"/>
<TextBox x:Name="txtOTHW" TextChanged="textChangedEventHandler"/>
I have set 2 breakpoints inside inside btnSave_Click on the if statements, started the solution, changed one of the textboxes and notice that whatever I do, both statements result in True. Even if I disable my textboxes and click on the save button, I still get True instead of False. When I attempt to debug I notice the following error on the TextChangedEvent, for one of the textboxes that I change:
I would really appreciate any suggestion. Thank you!
Attempt based on #user2107843 answer. It solves my initial problem, but when I click save the second time, it runs both stored procedures instead of only the one that as changed. So if I change txtAHW and then click save, it works, it only runs the stored procedure for txtAHW. If right after that I change txtOHW as well, the stored procedure runs for both instead for running only for txtOHW. My logic here is that txtAHW has already been saved so no need to run again. Can some help me improve this:
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
var control = sender as TextBox;
if (control.Name == "txtAHW")
if (oldAvgRate != txtAHW.Text && oldAvgRate != null)
txtAHWHasChangedFlag = true;
else
txtAHWHasChangedFlag = false;
else if (control.Name == "txtOTHW")
if (oldOTRate != txtOTHW.Text && oldOTRate != null)
txtOTHWHasChangedFlag = true;
else
txtOTHWHasChangedFlag = false;
}
You should make false in textChangedEventHandler
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
var control = sender as TextBox;
if (control.Name == "txtAHW" )
if(oldAvgRate != txtAHW.Text && oldAvgRate !=null)
txtAHWHasChangedFlag = true;
else
txtAHWHasChangedFlag = false
else if (control.Name == "txtOTHW")
txtOTHWHasChangedFlag = true;
}
I have a task to complete.. i must populate a list view from database and show in column wise and on a button click show it in a row wise... i just completed populating list view from database. now how do i display it it column wise and row wise... please help me...
This is the code i have tried to populate the database...
public partial class DtposMDIParentSystem : Form
{
List<object[]> result = new List<object[]>();
public DtposMDIParentSystem()
{
InitializeComponent();
//create the database connection
OleDbConnection aConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AP_AE\Desktop\DTPOS_APP\DataBase\DtposDatabase.accdb;");
//create the command object and store the sql query
OleDbCommand aCommand = new OleDbCommand("SELECT * FROM Food", aConnection);
try
{
aConnection.Open();
//create the datareader object to connect to table
OleDbDataReader reader = aCommand.ExecuteReader();
int i = 0;
while (reader.Read())
{
result.Add(new Object[reader.FieldCount]);
reader.GetValues(result[i]);
}
reader.Close();
aConnection.Close();
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Invalid Masseage = " + ex.Message);
}
}
private void cmdOlives_Click(object sender, EventArgs e)
{
if (result.Count > 0)
{
string temp = "";
for (int i = 0; i < result[1].Length; i++)
{
temp += result[1][i] + " ";
}
TableOrderListView.Items.Add(temp);
}
}
}
You can achieve something like that by switching between different view modes:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
listView1.View = View.Details;
listView1.HeaderStyle = ColumnHeaderStyle.None;
listView1.Columns[0].Width = listView1.ClientSize.Width - 25;
listView1.Height = 244;
}
else
{
listView1.View = View.List;
listView1.Columns[0].Width = 50;
listView1.Height = 44;
}
}
You need to add one Column for Details view to work!
Note that you will have to adapt the size of the Listview:
In Details mode it will need to be tall enough to show several items
In List mode it will have to to rather wide but must not be tall enough to show more than one item (plus the scrollbar)!
If instead you mean to switch rows and columns you will have to do that in your datasource!
I'm novice in c# and winforms, my idea is to create a simple app , which contains Form1 like this on image
There is dategridview where I can show data from database table Products(ID is not visible),then when I click on button New, Form2 will open
I want to use same Form2 when I want to edit some of the items, selecting specific row in datagridview and clicking on button Edit(I've managed to do this on 2 different win forms).How can I achieve this ?
This is what I've done so far:
button New
private void toolStripButton1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
f2.Show();
}
method PerformRefresh()
public void PerformRefresh()
{
this.productsTableAdapter.Fill(this.dbtestDataSet.products);
this.dataGridView1.Refresh();
}
Form2
Form1 _owner;
public Form2(Form1 owner)
{
InitializeComponent();
_owner = owner;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form2_FormClosing);
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
_owner.PerformRefresh();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
string Name = textBox1.Text;
int Quantity = Int32.Parse(textBox2.Text);
MySqlConnection cnn = new MySqlConnection(Konekcija.cnndbtest);
MySqlCommand cmd = new MySqlCommand("INSERT INTO products (Name,Quantity) VALUES(#name, #quantity)", cnn);
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#quantity", Quantity);
try
{
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception xcp)
{
MessageBox.Show(xcp.Message);
return;
}
MessageBox.Show("Object has been successfully entered into the database", "Message");
this.Close();
}
then, for button Edit on Form1 I've made class MyProducts , and made object of this class ,which I want to pass to Form2
MyProducts myProducts = new MyProducts();
myProducts.ID = Int32.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
myProducts.Name = dataGridView1.CurrentRow.Cells[1].Value.ToString();
myProducts.Quantity = Int32.Parse(dataGridView1.CurrentRow.Cells[2].Value.ToString());
Now I want to show Form2 clicking on button Edit , and when Form2 is shown, I want to have selected Item properties displayed into 2 textbox controls.
Any idea ?
Thanks in advance.
Give Form2 a public Property of MyProducts and fill the TextBoxes
private MyProducts product;
public MyProducts Product
{
set
{
product = value;
if (product != null)
{
nameTextBox.Text = product.Name;
quantityTextBox.Text = product.Quantity.ToString();
}
}
Then before opening the form for edit pass the MyProducts-Element you wanna edit
private void toolStripButton2_Click(object sender, EventArgs e)
{
MyProducts myProducts = new MyProducts();
myProducts.ID = Int32.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
myProducts.Name = dataGridView1.CurrentRow.Cells[1].Value.ToString();
myProducts.Quantity = Int32.Parse(dataGridView1.CurrentRow.Cells[2].Value.ToString());
Form2 f2 = new Form2(this);
f2.Product = myProducts;
f2.Show();
}
then on safe check if product has value to determine update or insert
private void toolStripButton1_Click(object sender, EventArgs e)
{
string Name = textBox1.Text;
int Quantity = Int32.Parse(textBox2.Text);
if (product != null)
{
//SQL Update command
}
else
{
//SQL Insert command
}
//SQL Execute
}
hope this helps
I created a grid view application and outside of my template I have a Add new row button. When i add a new row , it gets placed with an Edit and delete button. What I'm trying to do is when I click the add new row button, i want it to open the new row in editing mode, so no blank rows can be added with empty information. So basically if I add a new row and dont input information it wont be created.
If I need to be more thorough on my explanation please ask.
Any help will be appreciated.
Thank you
I ended up figuring out the problem on my own. It works perfect now. I as well changedup the database but I'm providing my code. Im sure there is an easier way but this was the best I could do: If you guys can provide inputs on an easier way I would appreciate it.
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
gv.DataBind();
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "", fundCode = "", BSA_CD = "", DP_TYPE = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
fundCode = d.Rows[0]["FUND_CD"].ToString();
BSA_CD = d.Rows[0]["BSA_CD"].ToString();
DP_TYPE = d.Rows[0]["DP_TYPE"].ToString();
if (transCode.Trim().Length > 0)
{
dbcon.Execute("INSERT INTO CIS.CIS_TRANS (TRANS_CD) VALUES('')", "ProjectCISConnectionString");
gv.DataBind();
}
}
gv.EditIndex = gv.Rows.Count - 1;
}
else if (e.CommandName == "Cancel")
{
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
if (transCode.Trim().Length == 0)
{
dbcon.Execute(string.Format("DELETE CIS.CIS_TRANS WHERE ID = '{0}'", d.Rows[0]["ID"]), "ProjectCISConnectionString");
gv.DataBind();
}
}
}
}
This is fairly simple, once you add the row:
You need to set the edit index of the newly added row:
gv.EditIndex = gv.Rows.Count-1;
Edit for OP
This is dirty code, I am just showing you what I mean and whipped it up fairly quickly.
Assume a gridview called GridView1 on your page:
namespace HelpSO3
{
public partial class _Default : System.Web.UI.Page
{
List<string> t = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string s = "hi";
t.Add(s);
GridView1.DataSource = t;
GridView1.DataBind();
Session["MyList"] = t;
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
t = (List<string>)Session["MyList"];
t.Add("Another String");
GridView1.DataSource = t;
GridView1.DataBind();
GridView1.EditIndex = GridView1.Rows.Count - 1;
GridView1.DataBind();
Session["MyList"] = t;
}
}
}
So the Button1_Click event adds a new row with the value "Another String" then we bind the grid view and set the EditIndex value to the newest row and rebind. Its that simple.
In your case your code would become:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
dbcon.Execute("INSERT INTO PROJ_ASP (TRANS_CD) VALUES('')", "ProjectASPConnectionString");
gv.DataBind();
gv.EditIndex = gv.Rows.Count-1;
gv.DataBind();
}
}