I have a problem in the form of my inventory system. Well it worked perfectly when one textbox was involved. But when there are 2 or more textbox involve it shows errors specifically: Truncated incorrect DOUBLE value: 'Knooks and Cranies'.
(Knooks and Cranies is an example of a supplier i inputted.)
I don't really know what's wrong because this is the 1st time I've encountered this error.
here's my code:
namespace SupplyRequestAndInventoryManagementSystem
{
public partial class DI_Assets : Form
{
connection con = new connection();
MySqlCommand cmd;
MySqlDataReader reader;
public DI_Assets()
{
InitializeComponent();
}
//load data from database
private void DI_Assets_Load(object sender, EventArgs e)
{
loadDepartment();
}
//checker
private void ListDelivery_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListDelivery.SelectedItems.Count > 0)
{
ListViewItem itm = ListDelivery.SelectedItems[0];
lblAssetIDChecker.Text = itm.SubItems[4].Text;
}
}
//load data from supplier
private void btnSearch_Click(object sender, EventArgs e)
{
loadtbl();
}
//add button
private void btnAdd_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to add new Delivery Information?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" || txtProdName.Text == "" || txtProdBrand.Text == "" || txtQty.Text == "" || DTPReceived.Text == "")
{
MessageBox.Show("Don't leave blanks!");
}
else
{
con.Close();
cmd = new MySqlCommand("Select * from deliver_mat where Del_MSupplier ='" + SuppNameCombo.Text + "' and Del_MName='" + txtProdName.Text + "' and Del_MBrand ='" + txtProdBrand.Text + "' and Del_MQty= '" + txtQty.Text + "' and Del_MReceived='" + DTPReceived.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
MessageBox.Show("Delivery Information already exist, sepcify a new one!");
}
else
{
addSection();
MessageBox.Show("Delivery Information successfully added!");
loadtbl();
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
}
else
{
MessageBox.Show("Adding new Delivery Information has been cancelled!");
}
}
//update button
private void btnUpdate_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to update the section?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" && txtProdName.Text == "" && txtProdBrand.Text == "" && txtQty.Text == "" && DTPReceived.Text == "")
{
MessageBox.Show("Please choose section to be updated!");
}
else
{
updateSection();
MessageBox.Show("Section has been successfully updated!");
loadtbl();
SuppNameCombo.Text = "";
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
else
{
MessageBox.Show("Updating section has been cancelled!");
}
}
//----------------------------------------------------------------------------------------------
//Retrieving Data from DB to listview
void loadtbl()
{
con.Close();
DataTable table = new DataTable();
cmd = new MySqlCommand("Select * from deliver_assets where Del_ASupplier = '" + SuppNameCombo.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
ListDelivery.Items.Clear();
while (reader.Read())
{
ListViewItem item = new ListViewItem(reader["Del_AName"].ToString());
item.SubItems.Add(reader["Del_ABrand"].ToString());
item.SubItems.Add(reader["Del_AReceived"].ToString());
item.SubItems.Add(reader["Del_AQty"].ToString());
item.SubItems.Add(reader["Del_aID"].ToString());
item.SubItems.Add(reader["Del_ASupplier"].ToString());
ListDelivery.Items.Add(item);
}
}
//Load Data to combo box
void loadDepartment()
{
con.Close();
DataTable table5 = new DataTable();
cmd = new MySqlCommand("Select Supp_Name from supply", con.con);
con.Open();
reader = cmd.ExecuteReader();
table5.Load(reader);
foreach (DataRow row in table5.Rows)
{
SuppNameCombo.Items.Add(row["Supp_Name"]);
}
}
//add function
void addSection()
{
con.Close();
cmd = new MySqlCommand("insert into deliver_assets(Del_AName, Del_ABrand, Del_AReceived, Del_AQty, Del_Asupplier) values('" + txtProdName.Text + "', '" + txtProdBrand.Text + "', '" + DTPReceived.Text + "', '" + txtQty.Text + "', '" + SuppNameCombo.Text + "')", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
//update function
void updateSection()
{
con.Close();
cmd = new MySqlCommand("update deliver_assets set Del_ASupplier ='" + SuppNameCombo.Text + "' and Del_AName ='" + txtProdName.Text + "' and Del_ABrand ='" + txtProdBrand.Text + "' and Del_AQty ='" + txtQty.Text + "' and Del_AReceived ='" + DTPReceived.Text + "' where Del_aID ='" + lblAssetIDChecker.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
}
}
Your code contains many errors that should be avoided in handling a database task:
Use of global variables for disposable object (in particular a
MySqlConnection)
No use of parameters
Incorrect syntax for the Update statement
Use of incorrect methods to Execute insert/update queries
Trying to use a do-it-all method to establish a connection (related
to first)
Thinking that a column with a specific datatype will happily accept a string as its value
To just give an example I will try to rewrite the Update code
//update function
void updateSection()
{
string cmdText = #"update deliver_assets
set Del_ASupplier =#sup.
Del_AName = #name,
Del_ABrand = #brand
Del_AQty = #qty
Del_AReceived = #recv
where Del_aID = #id";
using(MySqlConnection con = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, con))
{
cmd.Parameters.Add("#sup", MySqlDbType.VarChar).Value = SuppNameCombo.Text;
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = txtProdName.Text;
cmd.Parameters.Add("#brand", MySqlDbType.VarChar).Value = txtProdBrand.Text;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = Convert.ToDouble(txtQty.Text);
cmd.Parameters.Add("#recv", MySqlDbType.VarChar).Value = DTPReceived.Text;
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = Convert.ToInt32(lblAssetIDChecker.Text);
con.Open();
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowUpdated > 0)
MessageBox.Show("Record updated");
}
}
Note that I can't be sure about the correct datatype of your columns. You should create the parameter with the DataType compatible for your column changing the MySqlDbType values shown in the example above.
Related
So i'm writing a program with C# and Sql, i created a database in visual studio and DataSet, and connected it to DataGridView. But the problem is, when i insert something into DataGridView row, all strings are presented as question marks, but with "int" type everything is okay.
namespace MH
{
public partial class PatientForm : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Admin\source\repos\MH\MH\MH.mdf;Integrated Security=True");
public PatientForm()
{
InitializeComponent();
}
void populate()
{
conn.Open();
string query = "select * from Patient";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
PatientGV.DataSource = ds.Tables[0];
conn.Close();
}
private void label9_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void PatientForm_Load(object sender, EventArgs e)
{
populate();
PatientGV.Columns[0].HeaderText = "ID пациента";
PatientGV.Columns[1].HeaderText = "Имя";
PatientGV.Columns[2].HeaderText = "Адрес";
PatientGV.Columns[3].HeaderText = "Телефон";
PatientGV.Columns[4].HeaderText = "Возраст";
PatientGV.Columns[5].HeaderText = "Пол";
PatientGV.Columns[6].HeaderText = "Группа крови";
PatientGV.Columns[7].HeaderText = "Основная болезнь";
}
private void button4_Click(object sender, EventArgs e)
{
Home h = new Home();
h.Show();
this.Hide();
}
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
string query = "update Patient set PatName = '" + PatName.Text + "', PatAddress = '" + PatAd.Text + "', PatPhone = '" + PatPhone.Text + "', PatAge = '" + PatAge.Text + "', PatGender = '" + GenderCb.SelectedItem.ToString() + "', PatBlood = '" + BloodCb.SelectedItem.ToString() + "', PatDisease = '" + MajorTb.Text + "' where PatId = '" + PatId.Text + "'";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Пациент успешно обновлен");
conn.Close();
populate();
}
private void PatientGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.PatientGV.Rows[e.RowIndex];
PatId.Text = row.Cells[0].Value.ToString();
PatName.Text = row.Cells[1].Value.ToString();
PatAd.Text = row.Cells[2].Value.ToString();
PatPhone.Text = row.Cells[3].Value.ToString();
PatAge.Text = row.Cells[4].Value.ToString();
MajorTb.Text = row.Cells[7].Value.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (PatId.Text == "" || PatName.Text == "" || PatAd.Text == "" || PatPhone.Text == "" || PatAge.Text == "" || MajorTb.Text == "")
MessageBox.Show("Пустые поля не принимаются!");
else
{
conn.Open();
string query = "insert into Patient values(" + PatId.Text + ",'" + PatName.Text + "','" + PatAd.Text + "','" + PatPhone.Text + "'," + PatAge.Text + "," +
"'" + GenderCb.SelectedItem.ToString() + "','" + BloodCb.SelectedItem.ToString() + "','" + MajorTb.Text + "')";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Запись успешно добавлена!");
conn.Close();
populate();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (PatId.Text == "")
MessageBox.Show("Введите ID пациента");
else
{
conn.Open();
string query = "delete from Patient where PatId=" + PatId.Text + "";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Пациент успешно удален");
conn.Close();
populate();
}
}
}
}
I'll be glad to any help!
Edit: added code of the form for clarification
You can try the following steps to solve the problem about question marks in the datagirdview.
First, you could create the following table in your database.
CREATE TABLE [dbo].[Patient] (
[Id] INT NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Age] INT NOT NULL,
[Address] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Second, Please try the following code to use SqlParameters to insert data to database.
SqlConnection conn = new SqlConnection(#"CONNSTR");
void populate()
{
conn.Open();
string query = "select * from Patient";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
populate();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtId.Text == "" || txtName.Text == "" || txtAge.Text == "" || txtAddress.Text == "" )
MessageBox.Show("Пустые поля не принимаются!");
else
{
conn.Open();
string query = "insert into Patient(Id,Name,Age,Address)values(#Id,#Name,#Age,#Address)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#Id",Convert.ToInt32(txtId.Text));
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Age", Convert.ToInt32(txtAge.Text));
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Запись успешно добавлена!");
conn.Close();
populate();
}
}
Result:
What I had tried
I had tried using data adapter but it didn't work I tried using data reader but I am not sure on how to go about using it properly.
I want to get the value 12.0 to be saved and displayed into data grid view at the moment if I key 12.1 it also works only like 12.0 it will be entered and displayed as 12 at the data grid view
private void button1_Click(object sender, EventArgs e)
{
if (comboBoxstaff.Text == string.Empty)
{
MessageBox.Show("Please Select gaugeman"); // not to let thecombobox empty
return;
}
else if (comboBoxcompondrubber.Text == string.Empty)
{
MessageBox.Show("Please Select Compond Rubber");// not to let thecombobox empty
return;
}
else if (textBox1.Text == string.Empty)
{
MessageBox.Show("Please Key in W.S thickness");// not to let thetextbox empty
return;
}
else if (textBox2.Text == string.Empty)
{
MessageBox.Show("Please Key in G.S thickness");// not to let thecombobox empty
}
SQLiteConnection insertsess = new SQLiteConnection("Data Source=|DataDirectory|\\test1db");
string insert12 = "INSERT INTO thickness (GaugeMan,Dateandtime, CompondRubber,GSthickness,WSthicknes) VALUES ('" + comboBoxstaff.Text + "','" + label2.Text + "', '" + comboBoxcompondrubber.Text + "', '" + textBox2.Text + "', '" + textBox1.Text + "')"; //insert statment
SQLiteCommand ins1 = new SQLiteCommand(insert12, insertsess);
insertsess.Open();
ins1.ExecuteNonQuery();
MessageBox.Show("Data had been saved");// showed when the message is being saved
SQLiteConnection sesscheck = new SQLiteConnection("Data Source=|DataDirectory|\\test1db");
SQLiteCommand chk1;
chk1 = sesscheck.CreateCommand();
chk1.CommandText = "SELECT GaugeMan,Dateandtime, CompondRubber,GSthickness,WSthicknes FROM thickness WHERE CompondRubber = '" + comboBoxcompondrubber.Text.Trim() + "'";
sesscheck.Open();
DataTable thicknessTable = new DataTable();
//DataTable thicknessTable = new DataTable();
SQLiteDataReader reader = chk1.ExecuteReader();
thicknessTable.Load(reader);
//SQLiteDataReader reader1 = chk2.ExecuteReader();
//thicknessTable.Load(reader1);
sesscheck.Close();
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
I am trying to set up a method which allows me to archive a record which has been returned via a search box.
I have got the search query working however when I run the update query, the record still appears when searched for.
Can someone help?
namespace Test_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
MainMenu MMform = new MainMenu();
MMform.Show();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("SELECT Equipment.CustID AS CustID,Equipment.Manufacturer AS Manufacturer,Equipment.Model AS Model, Equipment.LastService AS LastService,Initial,Surname,[Address 1],[Address 2],[Address 3],[Post Town],[Post Code],Telephone FROM Contacts INNER JOIN Equipment ON Equipment.CustID = Contacts.CustID WHERE Contacts.Archived = 0 AND Surname = '" + textBox3.Text + "' OR Initial = '" + textBox3.Text + "' OR[Post Town] = '" + textBox3.Text + "' OR[Post Code] = '" + textBox3 + "'", conn);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int result;
customid.Text = reader["CustID"].ToString();
FirstName.Text = reader["Initial"].ToString();
LastName.Text = reader["Surname"].ToString();
Address1.Text = reader["Address 1"].ToString();
Address2.Text = reader["Address 2"].ToString();
Address3.Text = reader["Address 3"].ToString();
TownCity.Text = reader["Post Town"].ToString();
PostCode.Text = reader["Post Code"].ToString();
Telephone.Text = reader["Telephone"].ToString();
LstSvcDat.Text = reader["LastService"].ToString();
BoilMan.Text = reader["Manufacturer"].ToString();
BoilMod.Text = reader["Model"].ToString();
result = Convert.ToInt32(customid.Text);
}
}
finally
{
conn.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(LastName.Text))
{
MessageBox.Show("Please Search for a Customer First");
}
else
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("UPDATE Contacts SET Archived = 1 WHERE CustID = #CustID", conn);
command.Parameters.Add(new OleDbParameter("#PCustID", customid.Text));
OleDbDataReader reader = command.ExecuteReader();
}
finally
{
conn.Close();
customid.Text = null;
FirstName.Text = null;
LastName.Text = null;
Address1.Text = null;
Address2.Text = null;
Address3.Text = null;
TownCity.Text = null;
PostCode.Text = null;
Telephone.Text = null;
LstSvcDat.Text = null;
BoilMan.Text = null;
BoilMod.Text = null;
MessageBox.Show("Customer Archived");
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
I suspect the error is actually in your search query. When parenthesis are omitted the order of AND's and OR's are grouped. Try:
WHERE Contacts.Archived = 0 AND ((Surname = '" + textBox3.Text + "' OR Initial = '" + textBox3.Text + "') OR ([Post Town] = '" + textBox3.Text + "' OR[Post Code] = '" + textBox3 + "'))"
How to fix this problem? I don't know why this error occur when I already add Clode().
The error will go here:
public void existType()
{
try
{
con.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, con);
da.Fill(ds, "tblRoomType");
int counter = 0;
string tabletype = "tblRoomType";
if (counter < ds.Tables[tabletype].Rows.Count)
{
string type = ds.Tables[tabletype].Rows[counter]["Type"].ToString();
if (type == txtRoomType.Text)
{
editRoomType(); //There will be no error if I remove this and include the MessageBox below.
MessageBox.Show("Successfully Edited", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
//MessageBox.Show("This " + txtRoomType.Text + " is already exist.", "EXIST", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else //Remove this will remove the error
{
addRoomType();
MessageBox.Show("Successfully Added", "SUCCESS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}//to here
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This are the code of editRoomType() and addRoomType():
public void addRoomType()
{
con.Open();
string addtypequery = "INSERT INTO tblRoomType VALUES ('" + this.typeid + "','" + txtRoomType.Text + "','" + txtRoomRate.Text + "','" + txtExtraCharge.Text + "','" + txtCancelFee.Text + "','" + txtMaxOcc.Text + "')";
cmd = new OleDbCommand(addtypequery, con);
cmd.ExecuteNonQuery();
con.Close();
loadRoomType();
txtRoomType.ReadOnly = false;
txtRoomType.Enabled = false;
txtRoomRate.Enabled = false;
txtMaxOcc.Enabled = false;
txtExtraCharge.Enabled = false;
txtCancelFee.Enabled = false;
btnAddRoomType.Enabled = false;
txtRoomType.Clear();
txtRoomRate.Clear();
txtMaxOcc.Clear();
txtExtraCharge.Clear();
txtCancelFee.Clear();
}
public void editRoomType()
{
con.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, con);
cmd.ExecuteNonQuery();
con.Close();
}
The existType() will be go here:
private void btnAddRoomType_Click(object sender, EventArgs e)
{
if (txtRoomType.Text != "" || txtRoomRate.Text != "" || txtExtraCharge.Text != "" || txtCancelFee.Text != "" || txtMaxOcc.Text != "")
{
existType();
}
else
{
MessageBox.Show("Please fill in the space provided","OOPPSS!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The error is because you call con.Open in existType, then you either call addRoomType or editRoomType, both of which call con.Open again before you call con.Close in existType. Calling con.Open on an already open connection will throw the error you are seeing.
You can either remove the calls to con.Open/con.Close inside of the addRoomType or editRoomType and only call them in existType, or use local connections for each method, like so:
public void existType()
{
try
{
using (var conn = new SqlConnection())
{
conn.Open();
string existquery = "SELECT*FROM tblRoomType WHERE Type = '" + txtRoomType.Text + "'";
da = new OleDbDataAdapter(existquery, conn);
da.Fill(ds, "tblRoomType");
}
//rest of code
}
}
public void editRoomType()
{
using (var conn = new SqlConnection())
{
conn.Open();
string edittypequery = "UPDATE tblRoomType SET Rate = '" + txtRoomRate.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOcc = '" + txtMaxOcc.Text + "' WHERE TypeID = '" + txtRoomType.Text + "'";
cmd = new OleDbCommand(edittypequery, conn);
cmd.ExecuteNonQuery();
}
}
Note that you don't have to call Close since the using statement will do that for you.
Try like this -
try
{
con.Open();
.......
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Open();
}
}
I wanted to add an if statement to this code that says..
IF i click this button , it will check if the ListU.SelectedValue is empty or not , and if it is empty , a messagebox saying "please pick a name before continuing" , and if it is not empty , the code then runs.
how do i do that?
this is the code for the button click. (i know , my code needs some parameter , we can ignore that for the moment)
private void button4_Click(object sender, EventArgs e)
{
//update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = Int32.Parse(x);
int z = y + 1;
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
cmdC.ExecuteNonQuery();
conn.Close();
var ufdet = new UserFullDetail(ListU.SelectedValue.ToString());
ufdet.ShowDialog();
}
private void button4_Click(object sender, EventArgs e)
{
if(ListU.SelectedValue == null || ListU.SelectedValue.ToString() == string.Empty)
{
MessageBox.Show("Select something from the listbox, please");
return;
}
.....
Try like this
private void button4_Click(object sender, EventArgs e)
{
if(ListU.SelectedValue == null || ListU.SelectedValue.ToString() == string.Empty)
{
MessageBox.Show("Select something from the listbox, please");
}
else
{
//update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = Int32.Parse(x);
int z = y + 1;
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
cmdC.ExecuteNonQuery();
conn.Close();
var ufdet = new UserFullDetail(ListU.SelectedValue.ToString());
ufdet.ShowDialog();
}
}
I prefer this:
private void button4_Click(object sender, EventArgs e)
{
if (ListU.SelectedItem == null)
{
MessageBox.Show("Please pick a name before continuing.");
}
else
{
// Run the code.
}
}
This makes the else condition explicit, rather than implied as in Steve's example.
Another approach would be to only enable button4 if something is selected in ListU, e.g.,
private void ListU_SelectedIndexChanged(object sender, System.EventArgs e)
{
button4.Enabled = ListU.SelectedItem != null;
}
Try this:
private void button4_Click(object sender, EventArgs e)
{
if(ListU.SelectedValue == null || string.IsNullOrEmpty(Convert.ToString(ListU.SelectedValue)))
{
MessageBox.Show("Select something from the listbox.");
return;
}
.....