I have two forms where I have to get the date in the dategridview of the first form:
private void checkinToolStripMenuItem1_Click(object sender, EventArgs e)
{
int rowindex = dgCheckin.CurrentCell.RowIndex;
int reserveindex = 10;
string statindex = dgCheckin.Rows[rowindex].Cells[reserveindex].Value.ToString();
int roomindex = 5;
string roomNum = dgCheckin.Rows[rowindex].Cells[roomindex].Value.ToString();
if (statindex == "Reserved")
{
frmCheckIn recheckin = new frmCheckIn(user, true, roomNum);
recheckin.ShowDialog();
}
else if (statindex == "Cancelled")
{
MessageBox.Show("This " + roomNum + " is already cancelled.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Then the date will put in the datetimepicker in the second form:
public void loadReservation()
{
con.Open();
string reservetable = "tblReservation";
string reservequery = "SELECT*FROM tblReservation WHERE RoomNum = '" + this.roomnum + "' AND Status = 'Reserved'";
da = new SqlDataAdapter(reservequery, con);
da.Fill(ds, reservetable);
int counter = 0;
if (counter < ds.Tables[reservetable].Rows.Count)
{
string dateuse = ds.Tables[reservetable].Rows[counter]["DateOfUse"].ToString();
dtpCheckIn.Text = dateuse;
}
con.Close();
}
But the datetimepicker is not changing/same as what is in the database.
Related
I want when I enter the bar-code number without pressing any buttons automatically the data show up,and the quantity be 1 by default i tried the same with txt_no but it needs to press the enter button also.
here is the form.enter image description here
and here is the code:
private void txtno_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
txtqty.Enabled = true;
txtqty.Focus();
}
}
private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
try
{
string txt="Select * from products where id = '"+txtno.Text+"'";
MySqlCommand cmd = new MySqlCommand(txt,con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
int price = int.Parse(txtqty.Text.Trim()) * int.Parse(r[4].ToString());
totalprice = totalprice + price;
dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);
}
lbitems.Text = "" + (dataGridView1.RowCount - 1) + "";
lbtotal.Text = "" + totalprice + "";
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error From Database");
}
txtno.Focus();
txtno.Clear();
txtqty.Enabled = false;
txtqty.Clear();
}
}
You need TextChanged event handler for txtno(i.e. Bar-code textbox).
Add TextChanged event handler for txtno as below.
And as suggested by #HansKesting, you should sanitize inputs to avoid sql injection.
private void txtno_TextChanged(object sender, KeyPressEventArgs e)
{
if(!string.IsNullOrEmpty(txtno.Text))
{
txtqty.Enabled = true;
txtqty.Focus();
Search();
}
else
{
txtqty.Enabled = false;
}
}
private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
Search();
}
}
private void Search()
{
try
{
string txt = "Select * from products where id = '" + txtno.Text + "'";
MySqlCommand cmd = new MySqlCommand(txt, con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
int price = int.Parse(txtqty.Text.Trim()) * int.Parse(r[4].ToString());
totalprice = totalprice + price;
dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);
}
lbitems.Text = "" + (dataGridView1.RowCount - 1) + "";
lbtotal.Text = "" + totalprice + "";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error From Database");
}
txtno.Focus();
txtno.Clear();
txtqty.Enabled = false;
txtqty.Clear();
}
I am retrieving data from db and displaying in Label. but the problem is that this cannot retrieve db tabel first row data. Its print Second row data. If i given the db first row c_code then it is given the Error "There is no row at position 2" Kindly please solve my problem.
Thanks you
private void Get_Purchasing_Amount()
{
try
{
string get_P_Amount = "";
double var_P_Amount = 0;
int var_C_Code = 0;
string query = "select c_code as 'code' from `db_vegetable`.`tbl_payment_master`";
DataTable dt_C_Code = method_Class.method_Class.FetchRecords(query);
if (dt_C_Code.Rows.Count > 0)
{
for (int i = 0; i <= dt_C_Code.Rows.Count; i++)
{
var_C_Code = Convert.ToInt32(dt_C_Code.Rows[i]["code"]);
if (var_C_Code.Equals(Convert.ToInt32(txt_Customer_Code.Text)))
{
if (check_All.Checked.Equals(true))
{
get_P_Amount = "SELECT IFNULL(`purchasing`,0) AS 'purchasing' FROM `db_vegetable`.`tbl_payment_master` WHERE `c_code` = " + txt_Customer_Code.Text + "";
}
else
{
string dt_Query = "select `id` as 'id' from `db_vegetable`.`tbl_order_details`";
DataTable dt_C_O = method_Class.method_Class.FetchRecords(dt_Query);
if (dt_C_O.Rows.Count > 0)
get_P_Amount = "SELECT IFNULL(SUM(t_price),0) as 'purchasing' FROM `db_vegetable`.`tbl_order_details` WHERE `c_code` = " + txt_Customer_Code.Text + " AND (`date` BETWEEN '" + txt_From_Date.Text + "' AND '" + txt_To_Date.Text + "')";
else
lbl_Purchasing_Amount.Text = "0";
}
DataTable dt = method_Class.method_Class.FetchRecords(get_P_Amount);
var_P_Amount = Convert.ToDouble(dt.Rows[0]["purchasing"]);
lbl_Purchasing_Amount.Text = var_P_Amount.ToString();
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I believe this is probably the issue:
for (int i = 0; i <= dt_C_Code.Rows.Count; ; i++) {...}
Please consider substituting foreach (DataRow row in dt_C_Code.Rows) { ...}
If it's important which row should logically come "first", then please consider using an order by clause in your SQL statement.
Now problem is solve the problem is that break key word.
private void Get_Purchasing_Amount()
{
try
{
string get_P_Amount = "";
double var_P_Amount = 0;
//int var_C_Code = 0;
string query = "select c_code as 'code' from `db_vegetable`.`tbl_payment_master`";
DataTable dt_C_Code = method_Class.method_Class.FetchRecords(query);
if (dt_C_Code.Rows.Count > 0)
{
for (int i = 0; i <= dt_C_Code.Rows.Count; i++)//these line generate error please check this
{
//var_C_Code = Convert.ToInt32(dt_C_Code.Rows[i]["code"]);
if (Convert.ToInt32(dt_C_Code.Rows[i]["code"]).Equals(Convert.ToInt32(txt_Customer_Code.Text)))
{
if (check_All.Checked.Equals(true))
{
get_P_Amount = "SELECT IFNULL(`purchasing`,0) AS 'purchasing' FROM `db_vegetable`.`tbl_payment_master` WHERE `c_code` = " + txt_Customer_Code.Text + "";
}
else
{
string dt_Query = "select `id` as 'id' from `db_vegetable`.`tbl_order_details`";
DataTable dt_C_O = method_Class.method_Class.FetchRecords(dt_Query);
if (dt_C_O.Rows.Count > 0)
get_P_Amount = "SELECT IFNULL(SUM(t_price),0) as 'purchasing' FROM `db_vegetable`.`tbl_order_details` WHERE `c_code` = " + txt_Customer_Code.Text + " AND (`date` BETWEEN '" + txt_From_Date.Text + "' AND '" + txt_To_Date.Text + "')";
else
lbl_Purchasing_Amount.Text = "0";
}
DataTable dt = method_Class.method_Class.FetchRecords(get_P_Amount);
var_P_Amount = Convert.ToDouble(dt.Rows[0]["purchasing"]);
lbl_Purchasing_Amount.Text = var_P_Amount.ToString();
break;
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
catch (Exception)
{
}
}
I'm having problem setting the vertical scroll position. I have followed this similar question and I get the expected result for CellDoubleClick Event. But for KeyDown Event, where the user will press Enter key, it resets the vertical scroll position at the top
These are my CellDouble Click and KeyDown events.
private void dataGridSrch_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
addToSell();
}
}
private void dataGridSrch_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
addToSell();
}
This is my addToSell function, this function will call after that will update the DataGridView.
public void addToSell()
{
if (dataGridSrch.SelectedRows.Count > 0)
{
DataRow row = (dataGridSrch.SelectedRows[0].DataBoundItem as DataRowView).Row;
if (Convert.ToInt32(row["Stock"].ToString()) > 0)
{
string sellProd = row["Brand"].ToString() + " " + row["Part No."].ToString();
int sellQty = Convert.ToInt32(numSell.Value);
string sellUnit = row["Unit"].ToString();
double sellPrice = double.Parse(row["Price"].ToString()) * sellQty;
double sPrice = double.Parse(row["Price"].ToString());
dataGridSales.Rows.Add(sellProd, sellQty, sellUnit, sellPrice, sPrice, row["Part No."].ToString(), row["Stock"].ToString());
int count = 0;
double total = 0;
for (int i = 0; i < dataGridSales.Rows.Count; i++)
{
total += Convert.ToDouble(dataGridSales.Rows[i].Cells[3].Value);
count += Convert.ToInt32(dataGridSales.Rows[i].Cells[1].Value);
}
lblTotAmt.Text = "Total Amount: " + total.ToString("C2");
lblTotItem.Text = "Total Items: " + count;
amount = total;
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[products]
SET Stock = Stock - '" + sellQty + "' WHERE [Part No.] = '" + row["Part No."] + "'", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
>>>>>>>>>>>>>>>>after(); //THIS IS WHERE AFTER FUNCTION IS CALLED
}
else
{
MessageBox.Show("You dont have any stock for the selected item, please restock immediately.", "Please restock", MessageBoxButtons.OK);
}
}
if (dataGridSales.Rows.Count > 0)
{
cmbMOP.Enabled = true;
}
}
And this is my after function.
public void after()
{
string item = cmbItem.Text;
string brand = cmbBrand.Text;
string part = txtPart.Text;
string manu = cmbMan.Text;
string car = cmbCar.Text;
string year = cmbYr.Text;
conn.Open();
{
int index = dataGridSrch.SelectedRows[0].Index;
>>>>>>>>>>>>int scrollPos = dataGridSrch.FirstDisplayedScrollingRowIndex; //GET THE SCROLL POSITION
string sel = #"SELECT * FROM[dbo].[products] WHERE 1=1";
using (SqlCommand cmd = new SqlCommand())
{
if (!string.IsNullOrEmpty(item))
{
sel += " AND Item = #Item";
cmd.Parameters.Add("#Item", SqlDbType.VarChar).Value = item;
}
if (!string.IsNullOrEmpty(brand))
{
sel += " AND Brand = #Brand";
cmd.Parameters.Add("#Brand", SqlDbType.VarChar).Value = brand;
}
if (!string.IsNullOrEmpty(part))
{
sel += " AND [Part No.] = #Part";
cmd.Parameters.Add("#Part", SqlDbType.VarChar).Value = part;
}
if (!string.IsNullOrEmpty(manu))
{
sel += " AND Manufacturer = #Manufacturer";
cmd.Parameters.Add("#Manufacturer", SqlDbType.VarChar).Value = manu;
}
if (!string.IsNullOrEmpty(car))
{
sel += " AND Car = #Car";
cmd.Parameters.Add("#Car", SqlDbType.VarChar).Value = car;
}
if (!string.IsNullOrEmpty(year))
{
sel += " AND Year = #Year";
cmd.Parameters.Add("#Year", SqlDbType.VarChar).Value = year;
}
cmd.CommandText = sel;
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
DataView dv = dt.DefaultView;
sda.Fill(dt);
dataGridSrch.DataSource = dt;
dv.Sort = "Item, Brand, Manufacturer, Car, Year, Price ASC ";
dataGridSrch.Columns["Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridSrch.Columns["Price"].DefaultCellStyle.Format = "C2";
dataGridSrch.Columns["Stock"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridSrch.Rows[index].Selected = true;
>>>>>>>>>>>>>>>>>>>>dataGridSrch.FirstDisplayedScrollingRowIndex = scrollPos; //AFTER UPDATE SET THE SCROLL POSITION
typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null,
dataGridSrch, new object[] { true });
}
}
}
conn.Close();
}
I have also change my KeyDown Event to this
private void dataGridSrch_KeyDown(object sender, KeyEventArgs e)
{
int index = dataGridSrch.SelectedRows[0].Index;
int scrollPos = dataGridSrch.FirstDisplayedScrollingRowIndex;
if (e.KeyCode == Keys.Enter)
{
addToSell();
dataGridSrch.Rows[index].Selected = true;
dataGridSrch.FirstDisplayedScrollingRowIndex = scrollPos;
}
}
But still it resets the scroll position.
I have this code
*start time is another DateTime.now
*timeSinceStart is an array of timeSpan
*i believe that the for loop is for me to be able to create and store many values for the timespan and update the listview items(see link below for the photo of the form)
*f.ToString() is default 60(its an integer)
*the MH column in the picture is counting upwards, for ex. 1 2 3 4 5 6 etc etc
private void timer2_Tick(object sender, EventArgs e)
{
for (int w = 0; w < listView1.Items.Count; w++)
{
timeSinceStart[w] = DateTime.Now - startTime[w];
listView1.Items[w].SubItems[6].Text = (timeSinceStart[w].TotalSeconds.ToString());
if (f.ToString() == listView1.Items[w].SubItems[6].Text)
{
MessageBox.Show("dedede");
}
else
{
label3.Text = timeSinceStart[w].TotalSeconds.ToString();
}
}
I really cant make the message box pop up and also, the timespan value has decimal values, does it have a connection why the if condition doesn't trigger?
I have tried converting timespan to datetime and use datetime and timespan in the if else condition, it also doesnt seem to work.
here is the picture as i was saying:
edit*
I have another form that let the user to input an integer and a combobox that contains "Hour" of "Minute".
this is the code it contains:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please Indicate How Many Minutes/Hours.");
}
else
{
string desu = textBox1.Text;
int temp = 0;
if (int.TryParse(desu, out temp))
{
if (comboBox1.Text == "Hours")
{
//hours to seconds
time = temp * 3600;
eta = desu + " Hours";
sot = temp;
this.Close();
}
else if (comboBox1.Text == "Minutes")
{
//minutes to seconds
time = temp * 60;
eta = desu + " Minutes";
sot = temp;
this.Close();
}
}
else
{
MessageBox.Show("Please enter a valid integer");
}
}
}
And then i pass the value of "time" into the form mentioned above
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
ETA_Input frm = new ETA_Input(this);
frm.ShowDialog();
if (frm.time != 0)
{
string name = dataGridView1.CurrentRow.Cells[0].Value.ToString();
int deku = Int32.Parse(name);
string constring = "server=localhost;database=dbhorizon;uid=root;password=1234";
string Query = "update tblUserIdd set User_Available = 'Ongoing' where User_ID='" + deku + "' ";
MySqlConnection conDatabase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
MySqlDataReader myReader;
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
string id = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string naem = dataGridView1.CurrentRow.Cells[1].Value.ToString();
string field = dataGridView1.CurrentRow.Cells[2].Value.ToString();
f = frm.time;
if (stdex == 0)
{
startTime[stdex] = DateTime.Now;
stdex++;
}
else if (stdex >= 1)
{
startTime[stdex] = DateTime.Now;
stdex++;
}
secondss = string.Format("{0:t}", DateTime.Now);
string[] row = { id, naem, field, secondss, frm.eta,custb, f.ToString() };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
dgvref();
}
}
here.
i want to seatch by zone id and will it appear description, manager, division from database without searching in selecting from datagrid.
namespace Chemistlab.Addmanu
{
public partial class Zone : System.Web.UI.Page
{
string Sort_Direction = "ZoneID ASC";
public int ZoneID
{
get { return (int)ViewState["ZoneID"]; }
set { ViewState["ZoneID"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ZoneID = 0;
ViewState["SortExpr"] = Sort_Direction;
DataView dvStudents = Getdata(0);
GridVwPagingSorting.DataSource = dvStudents;
GridVwPagingSorting.DataBind();
int n = GridVwPagingSorting.Rows.Count;
}
}
protected void Save_OnClick(object sender, EventArgs e)
{
string Description = textdes.Text.Trim();
string Manager = textmanager.Text.Trim();
string Division = textdivision.Text.Trim();
string connectionString = ConfigurationManager.ConnectionStrings["ChemistlabConnectionString"].ConnectionString;
SqlCommand command = new SqlCommand();
SqlConnection Connection = new SqlConnection();
Connection.ConnectionString = connectionString;
Connection.Open();
command.Connection = Connection;
command.CommandType = CommandType.Text;
if (btnSave.Text == "Save")
{
command.CommandText = "insert into tblzone values ( '" + Description + "', '" + Manager + "','" + Division + "')";
}
else
{
command.CommandText = "update tblzone set Description = '" + Description + "', Manager = '" + Manager + "', Division ='" + Division + "' where ZoneID =" + ZoneID;
}
int i = command.ExecuteNonQuery();
Connection.Close();
if (i > 0)
{
lblmsg.Text = "Save data Successfully.";
textzoneid.Text = "";
textmanager.Text = "";
textdivision.Text = "";
textdes.Text = "";
btnSave.Text = "Save";
}
else
lblmsg.Text = "Unable to Save";
// show data to gridview
ViewState["SortExpr"] = Sort_Direction;
DataView dvStudents = Getdata(0);
GridVwPagingSorting.DataSource = dvStudents;
GridVwPagingSorting.DataBind();
int n = GridVwPagingSorting.Rows.Count;
}
private DataView Getdata(int zoneId)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ChemistlabConnectionString"].ToString()))
{
DataSet dsStudents = new DataSet();
string strSelectCmd = "";
if (zoneId > 0)
strSelectCmd = "SELECT [ZoneID],[Description],[Manager],[Division] FROM [tblzone] where ZoneID=" + zoneId;
else
strSelectCmd = "SELECT [ZoneID],[Description],[Manager], [Division] FROM [tblzone]";
SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, conn);
da.Fill(dsStudents, "tblzone");
DataView dvEmp = dsStudents.Tables["tblzone"].DefaultView;
dvEmp.Sort = ViewState["SortExpr"].ToString();
return dvEmp;
// foreach (GridView item in dvEmp.FindRows(ZoneID))
// {
// }
}
}
protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridVwPagingSorting.PageIndex = e.NewPageIndex;
DataView dvStudents = Getdata(0);
GridVwPagingSorting.DataSource = dvStudents;
GridVwPagingSorting.DataBind();
}
protected void Sorting(object sender, GridViewSortEventArgs e)
{
string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
if (SortOrder[0] == e.SortExpression)
{
if (SortOrder[1] == "ASC")
{
ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
}
else
{
ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
}
}
else
{
ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
}
GridVwPagingSorting.DataSource = Getdata(0);
GridVwPagingSorting.DataBind();
}
///protected void dataselect(object sender, GridViewSelectEventArgs e)
/// {
/// GridVwPagingSorting.ite
///}
protected void dataselect(object sender, EventArgs e)
{
try
{
if (GridVwPagingSorting.SelectedIndex != -1)
{
GridViewRow row = GridVwPagingSorting.SelectedRow;
Label lblzoneId = (Label)row.FindControl("lblzoneId");
Label lbldes = (Label)row.FindControl("lbldes");
Label lblmanager = (Label)row.FindControl("lblmanager");
Label lbldivsion = (Label)row.FindControl("lbldivsion");
//-----------------------Selected item Display To Text or Dropdown List ------------------------------------
ZoneID = Convert.ToInt32(lblzoneId.Text);
textzoneid.Text = lblzoneId.Text;
textdes.Text = lbldes.Text;
textmanager.Text = lblmanager.Text;
textdivision.Text = lbldivsion.Text;
btnSave.Text = "Update";
}
}
catch (Exception ex)
{
lblmsg.Text = "Faild to Select data";
}
}
protected void zoneid_TextChanged(object sender, EventArgs e)
{
ZoneID = Convert.ToInt32(textzoneid.Text);
//Getdata(Id);
DataView dvStudents = Getdata(ZoneID);
GridVwPagingSorting.DataSource = dvStudents;
GridVwPagingSorting.DataBind();
}
//protected void zoneid_OnTextChanged(object sender, EventArgs e)
//{
// ZoneID = Convert.ToInt32(textzoneid.Text);
// //Getdata(Id);
// DataView dvStudents = Getdata(ZoneID);
// GridVwPagingSorting.DataSource = dvStudents;
// GridVwPagingSorting.DataBind();
//}
}
}
Just execute an SQL Query against your database instead of looping through the items in the grid.
Query:
SELECT description, manager, division FROM [YOUR TABLE] WHERE ZONE_ID = [YOUR VALUE]