I have a windows form of controls combobox and datetimepicker..
I have given null or empty to combobox in page load..
so combobox shows empty intially while loading database values to it in windows form..
but the problem is
because of the datetimepicker is not kept to null or empty my form is showing message box as "the day is already existed" before form is desplaying..here my code follows
I want to show that message after combobox value is selected..
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("employee_id", typeof(string));
dt.Columns.Add("employee_name", typeof(string));
dt.Load(dtr);
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = null;
if(comboBox1.SelectedItem == null)
{
txtemployeeid.Text = "";
txtemployeename.Text = "";
}
cn.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select employee_id,Employee_name from Employee_Details where employee_name=('" + comboBox1.Text + "')", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
if (dtr.Read())
{
string employee_id = (string)dtr["employee_id"];
string employee_name = (string)dtr["employee_name"];
txtemployeeid.Text = employee_id;
txtemployeename.Text = employee_name;
dtr.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
if (comboBox1.SelectedItem != null)
{
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
SqlCommand cmd1 = new SqlCommand("select date from dailyattendance where date=('" + dtp + "') and employee_id='" + txtemployeeid.Text + "' and empployee_name='" + txtemployeename.Text + "' ", cn);
SqlDataReader dtr1;
dtr1 = cmd1.ExecuteReader();
if (dtr1.Read())
{
string date = (string)dtr1["date"];
if (dtp == date)
{
MessageBox.Show("this day is already existed");
}
}
dtr1.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
cn.Close();
}
can any one solve it please..Thanx in advance
You can simply use dtr.Text="";
Related
Basically, what I want to delete an entry form a dataviewtable which pulls data through from MySql. I thought this would be done fairly by effectively copying the modify code and substituting it for 'DELETE'. However, from the code below, you can clearly see that hasn't worked. I will copy most of my code for you:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HNR3NJB\\mysql;Initial Catalog=stock;Integrated Security=True");
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
con.Open();
sqlQuery = #"DELETE FROM [Products] WHERE [ProductID] = '" + textboxProductID.Text + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Record doesn't exist!", "ERROR:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Reading Data
LoadData();
}
So that's the delete button's code now for the add button and load data function
Add button:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//insert logic
con.Open();
if(textboxProductID.Text == "" || textboxProductName.Text == "")
{
MessageBox.Show("You have to enter either a product ID or product name", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
bool status = false;
if (comboboxStatus.SelectedIndex == 0)
{
status = true;
}
else
{
status = false;
}
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
sqlQuery = #"UPDATE [Products] SET [ProductName] = '" + textboxProductName.Text + "' ,[ProductStatus] = '" + status + "' WHERE [ProductID] = '" + textboxProductID.Text + "'";
}
else
{
sqlQuery = #"INSERT INTO [Stock].[dbo].[Products] ([ProductID],[ProductName],[ProductStatus]) VALUES
('" + textboxProductID.Text + "','" + textboxProductName.Text + "','" + status + "')";
}
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
textboxProductID.Clear();
textboxProductName.Clear();
LoadData();
}
}
LoadData function:
public void LoadData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//reading data from sql
SqlDataAdapter sda = new SqlDataAdapter("Select * From [stock].[dbo].[Products]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
if ((bool)item["ProductStatus"])
{
dataGridView1.Rows[n].Cells[2].Value = "Active";
}
else
{
dataGridView1.Rows[n].Cells[2].Value = "Deactive";
}
}
}
You're going to need the IfProductsExists method too:
private bool IfProductsExists(SqlConnection con, string productCode)
{
SqlDataAdapter sda = new SqlDataAdapter("Select 1 From [Products] WHERE [ProductID]='" + productCode + "'", con);
DataTable dt = new DataTable();
if (dt.Rows.Count > 0)
return true;
else
return false;
}
It's going to be an inventory system that's going to be used at work for the sale and inventory management of IT equipment.
im using the following code to populate a Gridview.I add 2 buttons for editing and deleting at the end.Hook to the click event.. but after i add the delete
button the click events are not firing.What im i doing wrong?
private void BindGrid2()
{
try
{
string constr = "Data Source=INSPIRE-1;" +
"Initial Catalog=testdatabase;" +
"User id=testuser;" +
"Password=tester;";
using (SqlConnection con = new SqlConnection(constr))
{
string commandText = "SELECT invnumber,itemname,quantity,rate FROM mytable2 where invnumber= #name";
using (SqlCommand command = new SqlCommand(commandText, con))
{
command.Parameters.AddWithValue("#name", text_inv.Text);
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
}
}
if (flag2 == false)
{
flag2 = true;
DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Edit";
uninstallButtonColumn.Text = "Edit";
dataGridView2.Columns.Insert(0, uninstallButtonColumn);
dataGridView2.Columns[0].DisplayIndex = 4;
DataGridViewButtonColumn uninstallButtonColumn2 = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Delete";
uninstallButtonColumn.Text = "Delete";
dataGridView2.Columns.Insert(5, uninstallButtonColumn2);
dataGridView2.Columns[5].DisplayIndex = 5;
}
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
string orderId;
if (e.ColumnIndex == 4)
{
try
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value;
using (SqlConnection conn = new SqlConnection(constr))
{
try
{
conn.Open();
SqlDataReader myReader = null;
string commandText = "select * from mytable2 where invnumber= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", text_inv.Text);
myReader = command.ExecuteReader();
while (myReader.Read())
{
text_cname.Text = myReader["cname"].ToString();
text_quantity.Text = myReader["quantity"].ToString();
text_item.Text = myReader["itemname"].ToString();
text_rate.Text = myReader["rate"].ToString();
dateTimePicker1.Text = myReader["date"].ToString();
// textBox4.Text = myReader["stock"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
catch (Exception error)
{
}
}
else if (e.ColumnIndex == 5)
{
using (SqlConnection conn = new SqlConnection(constr))
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value;
conn.Open();
SqlDataReader myReader = null;
string commandText = "delete from mytable2 where invnumber= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", text_inv.Text);
myReader = command.ExecuteReader();
}
BindGrid2();
}
}
Corrections below
dataGridView2.Columns.Insert(5, uninstallButtonColumn2) to dataGridView2.Columns.Insert(1, uninstallButtonColumn2)
if (e.ColumnIndex == 4) to if (e.ColumnIndex == 0)
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value; to orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[2].Value; at both the places
else if (e.ColumnIndex == 5) to else if (e.ColumnIndex == 1)
I am trying to retrieve data from a Database and show them on a form; but my code isn't working... I've got no errors, and logically it seems to work (to me) so I cannot figure out where I have gone wrong. That's where I need your help!
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
The 'tableListBox' is populated with all the values in column 'Default_Name'. I want it so that when the 'Default_Name' is selected from the list box it shows the values, in textboxes and comboboxes, that correspond with that row in the Database.
Any and all help would be appreciated. Thanks.
I'm going to start by changing your design a bit and suggest that perhaps you look at using a datatable and then just retrieving the rows from the datatable.
private void tableListBox_SelectedIndexChanged(object sender, EventArgs e)
{
private DataTable dataTable;
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE Default_Name = '" + tableListBox.SelectedValue + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
foreach(DataRow row in dataTable.Rows)
{
textBox1.Text = row[2].ToString();
comboBox1.Text = row[3].ToString();
comboBox3.Text = row[4].ToString();
textBox2.Text = row[6].ToString();
comboBox2.Text = row[7].ToString();
comboBox4.Text = row[8].ToString();
}
da.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I generally find that DataTables are more reliable than looping through the actual reader. Ofcourse this assumes that there is data being returned. Also try changing your select statement to this
string Query = "SELECT * FROM [Table]"
If that works, then the problem could be
There is no default name of the specified value or
tableListBox.SelectedValue is not returning any value, in which case, have a look at your listbox selected value
Thanks to Takarii for helping. I figured out who to make it work.
private void tableListBox_SelectedValueChanged(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\IncomerDefault.mdf;Integrated Security=True;Connect Timeout=30";
string Query = "SELECT * FROM [Table] WHERE ID = '" + tableListBox.SelectedIndex.ToString() + "'";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader Reader;
try
{
con.Open();
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
textBox1.Text = Reader.GetValue(2).ToString();
comboBox1.Text = Reader.GetValue(3).ToString();
comboBox3.Text = Reader.GetValue(4).ToString();
textBox2.Text = Reader.GetValue(6).ToString();
comboBox2.Text = Reader.GetValue(7).ToString();
comboBox4.Text = Reader.GetValue(8).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
First I changed the void to 'SelectedValueChanged' and then I changed the 'WHERE' in the connection Query to the Row Index associated with the selected Value.
Thanks for everyone's help!
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();
}
}
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