why it get old dataset - c#

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

Related

Reading specific row from MySql in C#

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

Winform DataGridView still shows data after final update

I'm developing a winform application using C#.net, using DataGridView to display the data, but after the last update, the DataGridView returns 1 last row, but i want my DataGridView to return a blank row or just show the header only...
nb: Before the update JmlKirimK value is 1.
try
{
con.Close();
con.Open();
MySqlCommand cmd = new MySqlCommand("Select PasienID, NoHP, JmlKirimK from datapasien where JmlKirimK ='1' AND StatusDiabetes='Ya'", con);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
con.Close();
con.Open();
nohp = Convert.ToString(dr[1]);
idpasien = Convert.ToString(dr[0]);
jml = Convert.ToString(dr[2]);
Cursor.Current = Cursors.WaitCursor;
if (objclsSMS.sendMsg(this.port2, nohp, this.txtisi.Text))
{
MySqlCommand cmd3 = new MySqlCommand("UPDATE datapasien SET JmlKirimK='2' Where PasienID='" + idpasien.Trim() + "'", con);
cmd3.ExecuteNonQuery();
terkirim = terkirim + 1;
showgridkirimulang();
}
else
{
tdkterkiri = tdkterkiri + 1;
}
showgridkirimreset();
}
con.Close();
alert.ContentImage = SmsGatewayProlanis.Properties.Resources.Warning1;
alert.CaptionText = "Status";
alert.ContentText = "Pesan Terkirim = " + terkirim + ", Pesan Tidak Terkirim = " + tdkterkiri;
alert.Show();
}
catch (Exception ex)
{
alert.ContentImage = SmsGatewayProlanis.Properties.Resources.Warning1;
alert.CaptionText = "Status";
alert.ContentText = ex.Message;
alert.Show();
ErrorLog(ex.Message);
}
This is my DataGridView code
private void showgridkirimulang()
{
con.Close();
con.Open();
MySqlCommand cmd = new MySqlCommand("SELECT NamaPasien, RiwayatPenyakit, AlamatPasien, UmurPasien, Jeniskelamin, NoHP, JmlKirimK, StatusDiabetes FROM datapasien WHERE JmlKirimK=1 AND StatusDiabetes='Ya'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
if (ds.Tables[0].Rows.Count > 0)
{
gridkirimulang.DataSource = ds.Tables[0];
gridkirimulang.Columns[0].HeaderText = "Nama Pasien";
gridkirimulang.Columns[1].HeaderText = "Riwayat Penyakit";
gridkirimulang.Columns[2].HeaderText = "Alamat Pasien";
gridkirimulang.Columns[3].HeaderText = "Umur Pasien";
gridkirimulang.Columns[4].HeaderText = "Jenis Kelamin";
gridkirimulang.Columns[5].HeaderText = "No. HP";
gridkirimulang.Columns[6].HeaderText = "Jumlah Pesan Terkirim";
gridkirimulang.Columns[7].HeaderText = "Status Diabetes";
gridkirimulang.MasterGridViewTemplate.BestFitColumns();
}
con.Close();
}

Showing alert panel when inventory reaches critical

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.

using dropdown menu sql statement not working

protected void btn_search_Click(object sender, EventArgs e)
{
using (con = new SqlConnection(CS))
{
string _var_search = ddl_search_by.SelectedItem.Text;
string _var_by = ddl_search.SelectedItem.Text;
cmd = new SqlCommand("Select * from UserProfile Where '"+_var_search+"'='" + _var_by + "'", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
Repeater1.DataSource = ds.Tables[0];
Repeater1.DataBind();
if (ds.Tables[0].Rows.Count > 0)
{
txt_not_found.Visible = false;
}
else
{
txt_not_found.Visible = true;
}
}
}
dont use quotes in first parameter:
cmd = new SqlCommand("Select * from UserProfile Where "+_var_search+"='" + _var_by + "'", con);
even better use paramaters:
cmd = new SqlCommand("Select * from UserProfile Where "+_var_search+"=#param", con);
cmd.Parameters.AddWithValue("#param", _var_by);

Increment Column Value in database using c# asp.net

How to increase totaldownloads value in my database file code is given below
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataRow dr;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserId"] == null)
{
lblMessage.Visible = true;
GridView1.Visible = false;
//AppContent.Visible = false;
}
else
{
if (!Page.IsPostBack)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
ArrayList myArrayList = ConvertDataSetToArrayList();
Literal objliteral = new Literal();
StringBuilder objSBuilder = new StringBuilder();
//Add some column to datatable display some products
dt.Columns.Add("appImg");
dt.Columns.Add("appName");
dt.Columns.Add("appLink");
dt.Columns.Add("appType");
dt.Columns.Add("TotalVisitors");
dt.Columns.Add("TotalDownloads");
dt.Columns.Add("RemainingVisitors");
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
//Add rows with datatable and bind in the grid view
dr = dt.NewRow();
dr["appImg"] = ((DataRow)row)["AppImg"].ToString();
dr["appName"] = ((DataRow)row)["AppName"].ToString();
dr["appLink"] = ((DataRow)row)["AppLink"].ToString();
dr["appType"] = ((DataRow)row)["AppType"].ToString();
dr["TotalVisitors"] = "Plan Visitors: " + ((DataRow)row)["TotalVisitors"].ToString();
dr["TotalDownloads"] = "Downloaded: " + ((DataRow)row)["TotalDownloads"].ToString();
dr["RemainingVisitors"] = "Remaining Visitors: " + ((DataRow)row)["RemainingVisitors"].ToString();
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
public ArrayList ConvertDataSetToArrayList()
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand cmd = new SqlCommand();
if (Session["UserId"] != null && (Session["UserTypeId"] != null && Convert.ToInt32(Session["UserTypeId"]) != 2))
{
cmd.CommandText = "Select * from tblApp WHERE AppType = '" + Session["UserOSType"] + "' ORDER BY TotalVisitors";
}
else
{
cmd.CommandText = "Select * from tblApp ORDER BY TotalVisitors";
}
cmd.Connection = sqlcon;
sqlcon.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet dsApp = new DataSet();
da.Fill(dsApp, "tblApp");
ArrayList myArrayList = new ArrayList();
foreach (DataRow dtRow in dsApp.Tables[0].Rows)
{
myArrayList.Add(dtRow);
}
sqlcon.Close();
return myArrayList;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "download")
{
Button ib = (Button)e.CommandSource;
int index = Convert.ToInt32(ib.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label l2 = (Label)row.FindControl("Label2");
Label lbTotallVisitors = (Label)row.FindControl("Label4");
Label lblTotalDownloads = (Label)row.FindControl("Label5");
Label lblRemainingVisitors = (Label)row.FindControl("Label6");
string updateSQL = "UPDATE tblUser SET DownloadedApps = '" + lbl + "', Amount = '" + Session["Amount"] + "', TotalAmount='" + Session["TotalAmount"] + "' WHERE Id= '" + Session["UserId"] + "'";
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString()))
{
using (SqlCommand updateCommand = new SqlCommand(updateSQL, sqlConn))
{
sqlConn.Open();
updateCommand.ExecuteNonQuery();
updateCommand.Connection.Close();
}
}
Response.Redirect(l2.Text);
}
}
UPDATE Table SET Column = Column + 1

Categories

Resources