updating column value in Ms-Access 2010 using c# and oledb query - c#

I am struggling for updating record/columnvalue in MS-ACCESS database... help would be appreciated a lot..!
I am displaying a list of partnumbers retrieved from a table in Ms-access using Datagridview in which I am supposed to update/change partnumber. ( 'partno' is 3rd column of my datagridview.)
But I am unable to Update a single record in database..no exceptions.. everything is going fine.!
But no rows are effected!
Here is my code:
private void UpdateDetails_Click(object sender, EventArgs e)
{
try
{
con = new OleDbConnection();
con.ConnectionString = Helper.MyConnectionString;
con.Open();
for (int i = 0; i <= datagridview1.Rows.Count-1; i++)
{
int j = i + 1; // j is the serial number corresponding to partnumber
string partno = dgv1.Rows[i].Cells[2].Value.ToString(); //getting part number from Datagridview
String partquery = "";
if (partno == null || partno == "") //checking whether part number updated or not
{
partquery = "update Vendor SET PartNo=NULL where Vendor.Sno=" + j + " ";
}
else
partquery = "update Vendor SET PartNo='" + partno + "' where Vendor.Sno=" + j + " ";
//Vendor is the table name containg 'partno' list
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = partquery;
cmd.ExecuteNonQuery();
}
}
catch(Exception ex)
{
//exception handler
}
}

As #Soner suggested you should use parameters. Something like this.
Modified the code did you do something like this?
private void UpdateDetails_Click(object sender, EventArgs e)
{
try
{
con = new OleDbConnection();
con.ConnectionString = Helper.MyConnectionString;
con.Open();
for (int i = 0; i <= datagridview1.Rows.Count - 1; i++)
{
int j = i + 1; // j is the serial number corresponding to partnumber
string partno = dgv1.Rows[i].Cells[2].Value.ToString(); //getting part number from Datagridview
//String partquery = "";
//if (partno == null || partno == "") //checking whether part number updated or not
//{
// partquery = "update Vendor SET PartNo=NULL where Vendor.Sno=" + j + " ";
//}
//else
// partquery = "update Vendor SET PartNo='" + partno + "' where Vendor.Sno=" + j + " ";
OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("update Vendor SET PartNo='#partno' where Vendor.Sno=#vndid");
OleDbParameter parameter = new System.Data.OleDb.OleDbParameter("#partno", partno);
cmd.Parameters.Add(parameter);
parameter = new System.Data.OleDb.OleDbParameter("#vndid", j);
cmd.Parameters.Add(parameter);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//exception handler
}
}

Related

How can i use HiddenField id as a variable for its value in c#

I have 1000 hiddenfield. How can i put their value in sql database using for loop. Like:
for (int i = 1; i < 1000; i++)
{
Control hiddenfield = this.FindControl("HiddenField" + i);
String p = Convert.ToString(hiddenfield.Value);
string sqlquery = ("INSERT INTO [" + table_name2 + "] (CT1) VALUES ('" + p + "')");
SqlCommand command = new SqlCommand(sqlquery, Connection);
command.ExecuteNonQuery();
}
change tablename as requred!
string query = "INSERT INTO tablename ( CT1 ) VALUES ( #value )";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query, con);
try
{
cmd.Parameters.Add("#value", System.Data.SqlDbType.VarChar);
con.Open();
for (int i = 1; i < 1000; i++)
{
Control hiddenfield = this.FindControl("HiddenField" + i);
String p = Convert.ToString(hiddenfield.Value);
cmd.Parameters["#value"].Value = p;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//Show exception as required!
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}

WPF disable rows duplicate in Datagrid using foreach loop

I want to check each row in unbound datagrid if cell value equal textbox value then dont add the row
using foreach loop
the problem now is that iam using unbound datagrid and cannot use the ItemSource in the foreach loop
and if i run the code below i got error :
System.InvalidCastException: 'Unable to cast object of type 'MyMasrof' to type 'System.Data.DataRow'.'
here is my code :
private void AddMaterial_btn_Click(object sender, RoutedEventArgs e)
{
if (Materials_Lookup.Text == null)
{
MessageBox.Show("Choose Item First");
}
else
{
if (Masrof_Grid.Items.Count > 0)
{
foreach (System.Data.DataRow dr in Masrof_Grid.Items)
{
if (dr["Masrof_Material_Name"].ToString() == StoreName_txt.Text)
{
MessageBox.Show("Item Already Exist");
}
else
{
MySqlConnection conn2 = new MySqlConnection("DataSource='" + DoSomething.Server_Param + "';UserID='" + DoSomething.Uid_Param + "';Password='" + DoSomething.Password_Param + "';Database='" + DoSomething.Database_Param + "';PORT=3306;CHARSET=utf8");
conn2.Open();
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader rd;
DataSet ds = new DataSet();
ds.Clear();
cmd.Connection = conn2;
cmd.CommandText = "SELECT id FROM Items where Item_Arabic_Name ='" + Materials_Lookup.Text + "'";
rd = cmd.ExecuteReader();
if (rd.Read())
{
Masrof_Grid.Items.Add(new MyMasrof()
{
Masrof_Material_Code = (rd["id"].ToString()),
Masrof_Material_Name = Materials_Lookup.Text,
Masrof_MAterial_QTY = QTY_txt.Text,
Masrof_Material_Store = StoreName_txt.Text,
MAterial_Curr_Balance = CurrBalance_txt.Text
});
}
else
{
MessageBox.Show("Cannot be found");
}
conn2.Close();
}
}
}
else
{
MySqlConnection conn2 = new MySqlConnection("DataSource='" + DoSomething.Server_Param + "';UserID='" + DoSomething.Uid_Param + "';Password='" + DoSomething.Password_Param + "';Database='" + DoSomething.Database_Param + "';PORT=3306;CHARSET=utf8");
conn2.Open();
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader rd;
DataSet ds = new DataSet();
ds.Clear();
cmd.Connection = conn2;
cmd.CommandText = "SELECT id FROM Items where Item_Arabic_Name ='" + Materials_Lookup.Text + "'";
rd = cmd.ExecuteReader();
if (rd.Read())
{
Masrof_Grid.Items.Add(new MyMasrof()
{
Masrof_Material_Code = (rd["id"].ToString()),
Masrof_Material_Name = Materials_Lookup.Text,
Masrof_MAterial_QTY = QTY_txt.Text,
Masrof_Material_Store = StoreName_txt.Text,
MAterial_Curr_Balance = CurrBalance_txt.Text
});
// decimal sum = 0m;
// for (int i = 0; i < Masrof_Grid.Items.Count; i++)
// {
// sum += (decimal.Parse((Masrof_Grid.Columns[7].GetCellContent(Masrof_Grid.Items[i]) as TextBlock).Text));
// }
//// txtSumReal.Text = sum.ToString();
}
else
{
MessageBox.Show("cannot be found");
}
conn2.Close();
}
}
}

data reader has rows but comparison of its values is never true

I am creating a module for booking rooms in hotel.After selecting the rooms, the room numbers appear in a label. On clicking the OK button, the following code executes. When I am checking the availability of rooms, even if it is "No", flag does'nt get initialized to 1. Can anyone guide me where am I going wrong.
protected void ok_room(object sender, EventArgs e)
{
if (Label1.Text != "")
{
int result = 0;
int flag = 0;
string[] room = Label1.Text.Split(new char[] { ' ' });
cmd = new SqlCommand();
cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd.Connection = con;
for (int i = 0; i < room.Length; i++)
{
cmd1.CommandText = "select room_availability from rooms where room_num='" + room[i] + "' ";
dr = cmd1.ExecuteReader();
while (dr.Read())
{
if (dr[0].ToString().Equals("No"))//this is not working
flag = 1;
}
dr.Close();
}
Response.Write(flag);
if (flag == 0)
{
for (int i = 0; i < room.Length; i++)
{
cmd.CommandText = "update rooms set room_availability='No' where room_num='" + room[i] + "'";
cmd.ExecuteNonQuery();
result = 1;
}
}
else
{
Label2.Text = "Some of the selected rooms are not available. Kindly try again";
Label1.Visible=false;
}
if (result == 1)
{
isRoomAvailable = true;
Label2.Text = " Room(s) " + Label1.Text + " is/are booked";
Label1.Visible = false;
}
}
else
Response.Write("<script>alert('Select a room first.')</script>");
}
I would do more of the logic in SQL, this would simplify the code:
// Create a condition looking like this: room_num IN('1', '2', '3')
string roomsCondition = "room_num IN (' + Label1.Text.Replace(" ", "', '") + "')";
cmd1.CommandText =
#"SELECT SUM(CASE WHEN room_availability='Yes' THEN 1 ELSE 0 END) As available,
SUM(CASE WHEN room_availability='No' THEN 1 ELSE 0 END) As not_available
FROM rooms WHERE " + roomsCondition;
This query returns the number of available and non available rooms. It should then be easier to formulate the logic than by the use of flags.
Also have a look at the ExecuteScalar method. It makes it even easier than with the query I have shown above:
using (SqlConnection conn = new SqlConnection(connString)) {
string sql = "SELECT COUNT(*) FROM rooms WHERE room_availability='Yes' AND " +
roomsCondition;
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
int availableRooms = (int)cmd.ExecuteScalar();
if (availableRooms > 0) {
cmd.CommandText =
#"UPDATE rooms
SET room_availability='No'
WHERE availability='Yes' AND " + roomsCondition;
cmd.ExecuteNonQuery();
} else {
...
}
}

Error: object type cannot be compared with an int

This is my table:
roomtype, number of rooms
Ac 10
I want to retrieve the value from the table and subtract the rooms by 1 and update the above table. How do I write the retrieval code in ASP.NET using C#?
This is the updated code. It is showing errors in dt.Rows[0]["no_of_rooms"] > 1 saying that an object type cannot be compared with an int. But on parsing this no_of_rooms to int the error remains the same.
public partial class Book_Room : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string type = DropDownList1.SelectedItem.ToString();
string name = TextBox2.Text;
string nop = DropDownList2.SelectedItem.ToString();
int num = int.Parse(nop);
string connectionString = WebConfigurationManager.ConnectionStrings["HMSConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string qry3 = "select * from availiability where RoomType=#type";
SqlCommand cmd3 = new SqlCommand(qry3, connection);
cmd3.Parameters.AddWithValue("#type", type);
cmd3.ExecuteReader();
SqlDataAdapter ad = new SqlDataAdapter(cmd3);
DataTable dt = new DataTable();
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["no_of_rooms"] > 1)
{
string qry = "insert into RoomType values('" + type + "','" + name + "','" + num + "') ";
SqlCommand cmd = new SqlCommand(qry, connection);
connection.Open();
int g = cmd.ExecuteNonQuery();
if (g != 0)
Label5.Text = "Reserved for" + name;
connection.Close();
string qry2 = "update availiability set RoomType=#type ,availiable_rooms=#av";
SqlCommand cmd2 = new SqlCommand(qry2, connection);
cmd2.Parameters.AddWithValue("#type", type);
cmd2.Parameters.AddWithValue("#av", dt.Rows[0]["no_of_rooms"] - 1);
connection.Open();
cmd2.ExecuteNonQuery();
connection.Close();
}
}
else
{
label5.Text = "No Rooms Availiable in " + type;
}
}
}
Change it to this (int)dt.Rows[0]["no_of_rooms"] > 1.
Or you can try
dt.Rows[0].Field<int>("no_of_rooms")>1
You are not using any of the other values returned from your query, so creating a SqlDataAdapater and filling a Table is a bit much.
I would recommend using ExecuteScalar instead. This returns a single value from the database.
string qry3 = "select * from availiability where RoomType=#type";
SqlCommand cmd3 = new SqlCommand(qry3, connection);
cmd3.Parameters.AddWithValue("#type", type);
object objCount = command.ExecuteScalar();
int count = objCount == null ? 0 : (int)objCount;
if (count > 0)
{
// Do other things
}

Input string was not in a correct format in Sales Order

I am having this problem
Input string was not in a correct format.
highlighted to the part of:
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
I am having a hard time figuring out what is the error, can you help me? Thank you very much.
Here is my set codes:
private void displayNavigate()
{
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
double dTotal = 0;
try
{
for (int nRow = 0; nRow <= grdDetails.Rows.Count - 1; nRow++)
{
dTotal = dTotal + Convert.ToDouble((grdDetails.Rows[nRow].Cells["Amount"].Value.ToString()));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
lblTotal.Text = string.Format("{0:#,##00.00}", dTotal);
}
//================================================================================
//================================================================================
private void DisplayOrder(int nOrderNo)
{
try
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText = "SELECT " +
"B.OrderNo, B.OrderDate, A.CustomerNo, " +
"A.CustomerName, A.CustomerAddress, B.PurchaseOrderNo, B.AgentName, B.Status " +
"FROM Customers AS A, Orders AS B " +
"WHERE A.CustomerNo = B.CustomerNo " +
"AND B.OrderNo ='" + nOrderNo + "'";
SqlDataReader dr = cmdSelect.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
txtOrderNo.Text = dr["OrderNo"].ToString();
dtpOrderDate.Value = Convert.ToDateTime(dr["OrderDate"].ToString());
txtCustomerNo.Text = dr["CustomerNo"].ToString();
txtCustomerName.Text = dr["CustomerName"].ToString();
txtCustomerAddress.Text = dr["CustomerAddress"].ToString();
txtPONo.Text = dr["PurchaseOrderNo"].ToString();
cboAgentName.Text = dr["AgentName"].ToString();
txtOrderStatus.Text = dr["Status"].ToString();
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//================================================================================
//================================================================================
private void DisplayOrderDetails(int nOrderNo)
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText =
"SELECT PackagingOutside, Quantity, Unit, ProductNo, ProductName, ProductSize, PackagingInside, " +
"SellingDiscount, SellingPrice, Amount FROM OrderDetails WHERE OrderNo = '"
+ nOrderNo + "'";
SqlDataAdapter daDetail = new SqlDataAdapter();
daDetail.SelectCommand = cmdSelect;
DataSet ds = new DataSet();
daDetail.Fill(ds, "OrderDetails");
grdDetails.DataSource = null;
grdDetails.DataSource = ds.Tables["OrderDetails"];
}
when you use Convert.ToInt16 you will get this exception if value does not consist of an optional sign followed by a sequence of digits (0 through 9)
Do a validation for inputs before proceed like below.
int orderNo;
if (int.TryParse(txtOrderNo.Text, out orderNo))
{
DisplayOrder(orderNo);
DisplayOrderDetails(orderNo);
}
Side Note :
don't share the SqlConnection create new instant when you need it and wrap it with using block like below
using (SqlConnection con = new SqlConnection(connectionString))
{
}
Use SQL Parameters
cmdSelect.CommandText = "SELECT * FROM Orders WHERE OrderNo = #OrderNo";
cmdSelect.Parameters.AddWithValue("#OrderNo", nOrderNo);
This means that the value in txtOrderNo.Text is not considered an integer. You will get this error if your textbox is empty.
Either check that the textbox contains data, or use the TryParse (http://msdn.microsoft.com/en-us/library/f02979c7.aspx) method
There are two things to consider,
Values entered in the textbox should be an integer in the range of 16 bit, if it can be bigger value, then you have to think of going to long, int32 etc.
Validate the textbox using TryParse() which will tell you whether it has valid value entered.

Categories