So i am quite new to programing overall but i am learning pretty quick, so what im stuck on right now is that i need to read from a SQL table but i only want to read a single row by a key inside of the database.
The code i have down here does the work but i am quite sure you can do this alot more smooth as this is not very clean.
How could i do this in another more simple way?
What i want for result is to add all rows in to their own strings so that i can more easy use them for labels and other information in my program.
private static MySqlConnection dbConn;
static string MySQLConnectionString = "Server='ip';Port='port';Database='name';User='user';Password='Password';SslMode='none'";
public static void InitializeDB()
{
dbConn = new MySqlConnection(MySQLConnectionString);
string commandSuperuser = "SELECT * FROM sl WHERE User=(1)";
string commandUserOne = "SELECT * FROM sl WHERE User=(1)";
string commandUserTwo = "SELECT * FROM sl WHERE User=(2)";
string commandUserThree = "SELECT * FROM sl WHERE User=(3)";
string commandUserFour = "SELECT * FROM sl WHERE User=(4)";
string commandUserFive = "SELECT * FROM sl WHERE User=(5)";
string commandUserSix = "SELECT * FROM sl WHERE User=(6)";
string commandUserSeven = "SELECT * FROM sl WHERE User=(7)";
string commandUserEight = "SELECT * FROM sl WHERE User=(8)";
MySqlCommand cmd1 = new MySqlCommand(commandSuperuser, dbConn);
dbConn.Open();
MySqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
UserSuperuserName = reader1["Name"].ToString() + " " + reader1["Lastname"].ToString();
UserSuperuserENumber = reader1["ENumber"].ToString();
UserSuperuserNumber = reader1["Number"].ToString();
UserSuperuserNickname = reader1["Nickname"].ToString();
UserSuperuserMail = reader1["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd2 = new MySqlCommand(commandUserOne, dbConn);
dbConn.Open();
MySqlDataReader reader2 = cmd2.ExecuteReader();
while (reader2.Read())
{
UserOneName = reader2["Name"].ToString() + " " + reader2["Lastname"].ToString();
UserOneENumber = reader2["ENumber"].ToString();
UserOneNumber = reader2["Number"].ToString();
UserOneNickname = reader2["Nickname"].ToString();
UserOneMail = reader2["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd3 = new MySqlCommand(commandUserTwo, dbConn);
dbConn.Open();
MySqlDataReader reader3 = cmd3.ExecuteReader();
while (reader3.Read())
{
UserTwoName = reader3["Name"].ToString() + " " + reader3["Lastname"].ToString();
UserTwoENumber = reader3["ENumber"].ToString();
UserTwoNumber = reader3["Number"].ToString();
UserTwoNickname = reader3["Nickname"].ToString();
UserTwoMail = reader3["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd4 = new MySqlCommand(commandUserThree, dbConn);
dbConn.Open();
MySqlDataReader reader4 = cmd4.ExecuteReader();
while (reader4.Read())
{
UserThreeName = reader4["Name"].ToString() + " " + reader4["Lastname"].ToString();
UserThreeENumber = reader4["ENumber"].ToString();
UserThreeNumber = reader4["Number"].ToString();
UserThreeNickname = reader4["Nickname"].ToString();
UserThreeMail = reader4["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd5 = new MySqlCommand(commandUserFour, dbConn);
dbConn.Open();
MySqlDataReader reader5 = cmd5.ExecuteReader();
while (reader5.Read())
{
UserFourName = reader5["Name"].ToString() + " " + reader5["Lastname"].ToString();
UserFourENumber = reader5["ENumber"].ToString();
UserFourNumber = reader5["Number"].ToString();
UserFourNickname = reader5["Nickname"].ToString();
UserFourMail = reader5["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd6 = new MySqlCommand(commandUserFive, dbConn);
dbConn.Open();
MySqlDataReader reader6 = cmd6.ExecuteReader();
while (reader6.Read())
{
UserFiveName = reader6["Name"].ToString() + " " + reader6["Lastname"].ToString();
UserFiveENumber = reader6["ENumber"].ToString();
UserFiveNumber = reader6["Number"].ToString();
UserFiveNickname = reader6["Nickname"].ToString();
UserFiveMail = reader6["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd7 = new MySqlCommand(commandUserSix, dbConn);
dbConn.Open();
MySqlDataReader reader7 = cmd7.ExecuteReader();
while (reader7.Read())
{
UserSixName = reader7["Name"].ToString() + " " + reader7["Lastname"].ToString();
UserSixENumber = reader7["ENumber"].ToString();
UserSixNumber = reader7["Number"].ToString();
UserSixNickname = reader7["Nickname"].ToString();
UserSixMail = reader7["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd8 = new MySqlCommand(commandUserSeven, dbConn);
dbConn.Open();
MySqlDataReader reader8 = cmd8.ExecuteReader();
while (reader8.Read())
{
UserSevenName = reader8["Name"].ToString() + " " + reader8["Lastname"].ToString();
UserSevenENumber = reader8["ENumber"].ToString();
UserSevenNumber = reader8["Number"].ToString();
UserSevenNickname = reader8["Nickname"].ToString();
UserSevenMail = reader8["Email"].ToString();
}
dbConn.Close();
MySqlCommand cmd9 = new MySqlCommand(commandUserEight, dbConn);
dbConn.Open();
MySqlDataReader reader9 = cmd9.ExecuteReader();
while (reader9.Read())
{
UserEightName = reader9["Name"].ToString() + " " + reader9["Lastname"].ToString();
UserEightENumber = reader9["ENumber"].ToString();
UserEightNumber = reader9["Number"].ToString();
UserEightNickname = reader9["Nickname"].ToString();
UserEightMail = reader9["Email"].ToString();
}
dbConn.Close();
}
If someone has any tips/examples that would be awesome.
You could use MysqlDataAdapter and DataTable and save the values to String arrays.
public static void InitializeDB()
{
dbConn = new MySqlConnection(MySQLConnectionString);
dbConn.Open();
try
{
using (MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM S1", dbConn))
{
DataTable dt = new DataTable();
da.Fill(dt);
int a = 0;
if (dt.Rows.Count > 0)
{
string[] UserName = new string[dt.Rows.Count];
string[] UserENumber = new string[dt.Rows.Count];
string[] UserNumber = new string[dt.Rows.Count];
string[] UserNickname = new string[dt.Rows.Count];
string[] UserMail = new string[dt.Rows.Count];
for (a = 0; a < dt.Rows.Count; a++)
{
UserName[a] = dt.Rows[a]["Name"].ToString();
UserENumber[a] = dt.Rows[a]["Enumber"].ToString();
UserNumber[a] = dt.Rows[a]["Number"].ToString();
UserNickname[a] = dt.Rows[a]["Nickname"].ToString();
UserMail[a] = dt.Rows[a]["Mail"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dbConn.Close();
}
}
Related
i dont have an edit template. is it possible for me to add validations on my text box in grid view during edit mode?
It updates the edited fields and works fine, but when I type in special characters, it is still being accepted. How can I validate those editableTextBoxes and prevent the user from entering invalid input?
UPDATE
int prodid = int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());
string strprodname = ((TextBox)gdview.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
//string strdesc = ((TextBox)gdview.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string strprice = ((TextBox)gdview.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
//string strimg = ((TextBox)gdview.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
//string strquant = ((TextBox)gdview.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
var regex = new Regex(#"^\d{0,8}(\.\d{1,4})?$");
if (regex.IsMatch(strprice))
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlDataAdapter da = new SqlDataAdapter("", conn);
conn.Open();
da.UpdateCommand = new SqlCommand("update Products set Name='" + strprodname + "', Price ='" + strprice + "' where ProductID =" + prodid, conn);
da.UpdateCommand.ExecuteNonQuery();
conn.Close();
gdview.EditIndex = -1;
GetProducts(0);
}
fields not updating
UPDATE getproducts(0)
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
gdview.DataSource = null;
gdview.DataSource = k.GetAllProducts();
gdview.DataBind();
}
datatable:
public DataTable GetAllProducts()
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataLayer.DataAccess.AddParameter("#CategoryID", CategoryID, System.Data.SqlDbType.Int, 20);
DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("SP_GetAllProducts", parameters);
return dt;
}
UPDATE:
Current Code:
protected void gdview_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int prodid = int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());
string strprodname = ((TextBox)gdview.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
//string strdesc = ((TextBox)gdview.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string strprice = ((TextBox)gdview.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
//string strimg = ((TextBox)gdview.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
//string strquant = ((TextBox)gdview.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
var regex = new Regex(#"^\d{0,8}(\.\d{1,4})?$");
if (regex.IsMatch(strprodname) && regex.IsMatch(strprice))
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlDataAdapter da = new SqlDataAdapter("", conn);
conn.Open();
da.UpdateCommand = new SqlCommand("update Products set Name='" + strprodname + "', Price ='" + strprice + "' where ProductID =" + prodid, conn);
da.UpdateCommand.ExecuteNonQuery();
conn.Close();
gdview.EditIndex = -1;
}
GetProducts(0);
}
var regex_valid_price = new Regex(#"^\d{0,8}(\.\d{1,4})?$");
var regex_no_special_chars = new Regex(#"^[a-zA-Z0-9 ]*$");
if(regex_no_special_chars.IsMatch(strprodname) && regex_valid_price.IsMatch(strprice)){
// do your db inserts
}
Visit http://demos.telerik.com/aspnet-ajax/grid/examples/data-editing/validation/defaultcs.aspx
you may get the solution.
I'm trying to show when an inventory is lower than critical. It doesn't seem to get there when I debug the system
This is my code behind
protected void Page_Load(object sender, EventArgs e)
{
GetInventory();
TotalCount();
CriticalItem();
Panel1.Visible = false;
}
void TotalCount()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT 'Total Count of Inventory ' + '(' + convert(nvarchar,SUM(Quantity)) + ')' AS TotalCount from Inventory";
SqlDataReader data = cmd.ExecuteReader();
if (data.HasRows)
{
while (data.Read())
{
lblTotalCount.Text = data["TotalCount"].ToString();
}
con.Close();
}
else
{
con.Close();
Response.Redirect("Default.aspx");
}
}
void GetInventory()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Inventory.InventoryID, Products.ProductName, " +
"Supplier.SupplierName, Inventory.Quantity, Users.LastName + ', ' + Users.FirstName AS UserAccount, " +
"SupplierProducts.CriticalLevel, Inventory.Status, Inventory.DateAdded, Inventory.DateModified, SupplierProducts.Price FROM Inventory " +
"INNER JOIN SupplierProducts ON Inventory.ProductID = SupplierProducts.SupplierProductID " +
"INNER JOIN Products ON SupplierProducts.ProductID = Products.ProductID " +
"INNER JOIN Supplier ON Inventory.SupplierID = Supplier.SupplierID " +
"INNER JOIN Users ON Inventory.UserID = Users.UserID";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Inventory");
lvInventory.DataSource = ds;
lvInventory.DataBind();
con.Close();
}
void CriticalItem()
{
var intcheck = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM Inventory", con))
{
da.Fill(intcheck);
}
var critcheck = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM SupplierProducts", con))
{
da.Fill(critcheck);
}
int finalQuantity = Convert.ToInt32(intcheck.Rows[0]["Quantity"]);
int criticalLevel = Convert.ToInt32(critcheck.Rows[0]["CriticalLevel"]);
if (finalQuantity > criticalLevel)
{
Panel1.Visible = true;
criticalItem.Text = "Available";
}
}
I want to criticalItem.text to tell the Inventory that is less than its critical level.
I wanted to update my database that contains two text and one filename that is needed for image.
The problem is that the image and filename updates but the two other text values title and body wont be affected and don't change the previous values. Also visual studio don't get any problem and the message for executing command shows that it's executed the command but nothing except the image changes.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("~/default.aspx");
if (Request .QueryString ["action"]=="edit")
{
Panel1.Visible = true;
}
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString =GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString () + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text=myReader ["Title"].ToString ();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
protected void btn_addpost_Click(object sender, EventArgs e)
{
string title= title_txt .Text ;
string body=bodytxt .Text ;
if (Request.QueryString["edit"] != null)
{
string message;
string filename = thumb_uploader.FileName;
string path = HttpContext.Current.Server.MapPath("~") + "\\Thumb";
string exup = System.IO.Path.GetExtension(thumb_uploader.FileName);
string[] ext = { ".jpg", ".png", ".jpeg" };
if (Array.IndexOf(ext, exup) < 0)
{
message = "not correct.";
}
if (thumb_uploader.FileBytes.Length / 1024 > 400)
{
message = "not currect.";
}
while (System.IO.File.Exists(path + "\\" + filename + exup))
{
filename += "1";
}
savepath = path + "\\" + filename;
if (thumb_uploader.HasFile)
{
thumb_uploader.SaveAs(savepath);
thumb = thumb_uploader.FileName;
SqlCommand command;
SqlDataAdapter da;
SqlConnection con3 = new SqlConnection();
con3.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
command = new SqlCommand();
command.Connection = con3;
da = new SqlDataAdapter();
da.SelectCommand = command;
command.CommandText = "UPDATE tbl_post SET Title=#title ,Body=#body ,Thumb=#thu Where Postid=" + Request.QueryString["edit"].ToString();
con3.Open();
command.Parameters.AddWithValue("#title", title );
command.Parameters.AddWithValue("#body", body );
command.Parameters.AddWithValue("#thu", thumb_uploader .FileName);
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
else
{
using (SqlConnection con3 = new SqlConnection(GNews.Properties.Settings.Default.connectionstring))
{
string sql = "update tbl_post SET Title=#title ,Body=#body Where Postid=#postid" ;
using (SqlCommand command = new SqlCommand(sql, con3))
{
con3.Open();
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#body", body);
command.Parameters.AddWithValue("#postid", Request.QueryString["edit"].ToString());
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
}
}
}
I've found the answer I needed this code to include my pageload reading database so it wouldn't do it when I click on the update button.I mean the problem was all about the post back thing.
if (!Page.IsPostBack)
{
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString() + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text = myReader["Title"].ToString();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
}
i have a table with 3 columns(EmpId,EmpName,EmpSalary).
i am using a prepared statement to retrieve all the data from this table using prepared statement.
here is what i have written...
try
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT EmpId,EmpName,EmpSalary FROM EmpDetails";
SqlParameter paraId = new SqlParameter();
paraId.ParameterName = "#id";
paraId.SqlDbType = SqlDbType.Int;
paraId.Size = 32;
SqlParameter paraName = new SqlParameter();
paraName.ParameterName = "#name";
paraName.SqlDbType = SqlDbType.VarChar;
paraName.Size = 50;
SqlParameter paraSal = new SqlParameter();
paraSal.ParameterName = "#sal";
paraSal.SqlDbType = SqlDbType.Decimal;
paraSal.Precision = 7;
paraSal.Scale = 2;
cmd.Parameters.Add(paraId);
cmd.Parameters.Add(paraName);
cmd.Parameters.Add(paraSal);
con.Open();
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
string str = "";
while(dr.Read())
{
string id = dr.GetInt32(0).ToString();
string name = dr.GetString(1);
string sal = dr.IsDBNull(2) ? "is null" : dr.GetDecimal(2).ToString();
str += id + "\t" + name + "\t" + sal + "\n";
}
MessageBox.Show(str);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
but i am getting an error as follows :
"The parameterized Query expects the parameter #id , which was not supplied."
What mistake am i doing here..??
Please use cmd.Parameters.AddWithValue(). Using cmd.Parameters.Add() is deprecated. Google its uses :-)
I checked your code, you will need to supply parameters value like below.
try
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT EmpId,EmpName,EmpSalary FROM EmpDetails ";
SqlParameter paraId = new SqlParameter();
paraId.ParameterName = "#id";
paraId.SqlDbType = SqlDbType.Int;
paraId.Size = 32;
SqlParameter paraName = new SqlParameter();
paraName.ParameterName = "#name";
paraName.SqlDbType = SqlDbType.VarChar;
paraName.Size = 50;
SqlParameter paraSal = new SqlParameter();
paraSal.ParameterName = "#sal";
paraSal.SqlDbType = SqlDbType.Decimal;
paraSal.Precision = 7;
paraSal.Scale = 2;
//i assume you forgot to setup parameter values.
paraId.Value = 1;
paraName.Value = "thisName";
paraSal.Value = 343;
cmd.Parameters.Add(paraId);
cmd.Parameters.Add(paraName);
cmd.Parameters.Add(paraSal);
con.Open();
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
string str = "";
while (dr.Read())
{
string id = dr.GetInt32(0).ToString();
string name = dr.GetString(1);
string sal = dr.IsDBNull(2) ? "is null" : dr.GetDecimal(2).ToString();
str += id + "\t" + name + "\t" + sal + "\n";
}
MessageBox.Show(str);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
My program is working normally when I select a listbox item.it getting datas correct dataset and correctly.when I write to textbox,my source method working and finding right results.but after when I selected listbox item it bringing old dataset datas to screen.What can I do in this methods?
public void ara(string str, int neyegore)
{
sqlcon.Open();
if (neyegore == 0)
komut = new SqlCommand("select * from FilmTablo WHERE ad LIKE '%" + str + "%'", sqlcon);
else if (neyegore == 1)
komut = new SqlCommand("select * from FilmTablo WHERE tur LIKE '%" + str + "%'", sqlcon);
else if (neyegore == 2)
komut = new SqlCommand("select * from FilmTablo WHERE yonetmen LIKE '%" + str + "%'", sqlcon);
else if (neyegore == 3)
komut = new SqlCommand("select * from FilmTablo WHERE oyuncular LIKE '%" + str + "%'", sqlcon);
sdr = null;
sdr = komut.ExecuteReader();
dt2 = new DataTable();
dt2.Load(sdr);
ds2 = new DataSet();
ds2.Tables.Add(dt2);
listBox1.Items.Clear();
// sayac2 = 1;
int i = 0;
while (i < ds2.Tables[0].Rows.Count)
{
listBox1.Items.Add(ds2.Tables[0].Rows[i].ItemArray[0]);
i++;
}
sqlcon.Close();
}
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
txtad.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[0].ToString().Trim();
txttur.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[1].ToString().Trim();
txtsure.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[2].ToString().Trim();
txtyonetmen.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[3].ToString().Trim();
txtoyuncular.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[4].ToString().Trim();
txtsenaryo.Text = ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[5].ToString().Trim();
byte[] resim = (byte[])ds.Tables[1].Rows[listBox1.SelectedIndex].ItemArray[7];
image1.Source = GetBitmapImage(resim);
}
public void listeyiguncelle()
{
sqlcon.Open();
komut = new SqlCommand("select * from FilmTablo", sqlcon);
sdr = null;
sdr = komut.ExecuteReader();
dt = new DataTable();
dt.Load(sdr);
ds = new FilmDataDataSet();
ds.Tables.Add(dt);
listBox1.Items.Clear();
int i = 0;
//MessageBox.Show(ds.Tables[1].Rows.Count.ToString());
while (i < ds.Tables[1].Rows.Count)
{
listBox1.Items.Add(ds.Tables[1].Rows[i].ItemArray[0]);
i++;
}
sqlcon.Close();
lblfilmsayisi.Content = ds.Tables[1].Rows.Count;
}