The first one is funtion that i call. second one is the code to show the data that has already been stored in database. Now when i input the license number from the txtno and select the License number from combobox cbonumber and press the btnsearch, there is no record found message is shown even though the licensenumber and numbertype exists is database
function
public DataTable CheckExistingLicenseNo(string LicenseNumber, string Numbertype)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=tprojectDB;");
string sql = "select *from tblDDDDDriver where LicenseNumber=#LicenseNumber and Numbertype=#Numbertype";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#LicenseNumber", LicenseNumber);
cmd.Parameters.AddWithValue("#Numbertype", Numbertype);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable db = new DataTable();
da.Fill(db);
return db; ;
}
code in btnsearch
private void btnsearch_Click(object sender, EventArgs e)
{
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.Text);
if (db.Rows.Count > 0)
{
if (cbonumbertype.Text == "LicenseNumber")
{
txtlicenseno.Text = db.Rows[0]["LicenseNumber"].ToString();
txtlicensecategory.Text = db.Rows[0]["LicenseCategory"].ToString();
txtissuedate.Text = db.Rows[0]["IssueDate"].ToString();
txtrenewdate.Text = db.Rows[0]["RenewDate"].ToString();
txtfullname.Text = db.Rows[0]["FullName"].ToString();
txtdob.Text = db.Rows[0]["DOB"].ToString();
txtaddress.Text = db.Rows[0]["Address"].ToString();
string gender = db.Rows[0]["Gender"].ToString();
if (gender == "Male")
{
txtgender.Text = " MALE";
}
else
{
txtgender.Text = "FEMALE";
}
txtvehicleno.Text = db.Rows[0]["VehicleNumber"].ToString();
txthealthstaus.Text = db.Rows[0]["HealthStatus"].ToString();
txtdrivertype.Text = db.Rows[0]["DriverType"].ToString();
Image img;
byte[] bytimg = (byte[])db.Rows[0]["Image"];
//convert byte of imagedate to Image format
using (MemoryStream ms = new MemoryStream(bytimg, 0, bytimg.Length))
{
ms.Write(bytimg, 0, bytimg.Length);
img = Image.FromStream(ms, true);
pictureBox1.Image = img;
}
}
DataTable dd = dc.GetMaxDeathNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dd.Rows.Count > 0)
{
txtdeathaccidentno.Text = dd.Rows[0]["DeathNumber"].ToString();
}
DataTable dM = dc.GetMaxMajorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dM.Rows.Count > 0)
{
txtmajoraccidentno.Text = dM.Rows[0]["MajorNumber"].ToString();
}
DataTable dm = dc.GetMaxMinorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dm.Rows.Count > 0)
{
txtminoraccidentno.Text = dm.Rows[0]["MinorNumber"].ToString();
}
DataTable dtrb = dc.GetTrafficRuleBroken(Convert.ToDecimal(txtlicensenumber.Text));
{
dataGridView1.DataSource = dtrb;
}
}
else
{
MessageBox.Show("No RECORD IS FOUND");
}
}
}
The only thing I suspect can be causing an issue is the value of cbonumbertype.Text. Change to cbonumbertype.SelectedValue and see if that wont help.
Change
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.Text);
To
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.SelectedValue);
I suspect that Bayeni's solution is the right one. You are possibly entering the ComboBox SelectedItem.Text value instead of the SelectedItem.Value value.
The easiest way to check this is to add a breakpoint to this line:
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.Text);
In Visual Studio, select Debug > Start Debugging and check if the value in cbonumbertype.Text is the one that you expect to see.
Related
I'm trying to Iterate through rows in a 2 column table to check 1 field in each row against a Name. Once found I want to code to assign the corresponding Number to the OurNumber variable, and break out of the loop by setting GotTheNumber to true.
Below is the code I'm using:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
DataTable table = new DataTable();
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
{
string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(table);
}
string SelectedName = DropBoxEmp.Text;
bool GotTheNumber = false;
int OurNumber = 0;
while (!GotTheNumber)
{
foreach (DataRow ThisRow in table.Rows)
{
if (SelectedName = (table.Rows[ThisRow]))
{
OurNumber = ///THATNUMBER///;
GotTheNumber = true;
}
}
}
MessageBox.Show(SelectedName);
var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());
form.PassValueName = SelectedName;
form.PassSelectedPayroll = GoodNumber;
form.Tag = this;
form.Show(this);
Hide();
}
I don't know where to go from the If statement, so any help would be greatly appreciated.
Looping through the rows in your client program is exactly what you don't want to do. Let the database do that work for you. Try this:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
object result;
string query = "SELECT PayrollNo FROM [Employee] WHERE FirstName + ' ' + LastName = ?";
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
//guessing at type and length here
cmd.Parameters.Add("?", OleDbType.VarWChar, 50).Value = DropBoxEmp.Text;
conn.Open();
result = cmd.ExecuteScalar();
}
if (result != null && result != DBNull.Value)
{
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
form.PassValueName = DropBoxEmp.Text;
form.PassSelectedPayroll = (int)result;
form.Tag = this;
form.Show(this);
Hide();
}
}
If you really want to loop through the rows against all reason (it's slower, requires writing more code, and it's more error-prone), you can do this:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
DataTable table = new DataTable();
string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
{
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(table);
}
int PayrollNumber = 0;
foreach (DataRow ThisRow in table.Rows)
{
if (DropBoxEmp.Text == ThisRow["NAME"])
{
PayrollNumber = (int)ThisRow["PayrollNo"];
break;
}
}
//the whole loop could also be consolidated to this:
//PayrollNumber = (int)table.Rows.First(r => r["NAME"] == DropBoxEmp.Text)["PayrollNo"];
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
form.PassValueName = DropBoxEmp.Text;
form.PassSelectedPayroll = PayrollNumber ;
form.Tag = this;
form.Show(this);
Hide();
}
Hm, hard to guess what exactly your problem is. But I think you just want to get the PayrollNo from the current row, aren't you?
Regarding the line further down ...
var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());
... I think you could just call:
if (...)
{
OurNumber = ThisRow["PayrollNo"].ToString();
GotTheNumber = true;
}
However, I have no clue what you are doing with the following if-condition and if this really does what you want it to do:
if (SelectedName = (table.Rows[ThisRow]))
{
...
}
I'm having a small problem. I want to get image data to display in an Image control from my Sql table when clicking on a ListView control row. I am using C# WPF and Microsoft SQL.
Now I can already insert the image into my database but the issue that I am having is that I can't seem to retrieve the image data once I click on a row in my ListView?
Here is the coding that I have tried...
This is the coding I use to fill the ListView:
private void FillEmployeeListView()
{
string ConString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string CmdString = string.Empty;
using (SqlConnection CON = new SqlConnection(ConString))
{
CmdString = "SELECT EmployeeEmailAddress, EmployeePassword, EmployeeDepartment, EmployeeIDNumber, EmployeeName, EmployeeSurname, EmployeeGender, EmployeeDOB, EmployeeHomeAddress, EmployeeTelephoneNumber, EmplyeeCity, EmployeeProvinceCode, EmployeeProfilePicture FROM Main.tblEmployeeLoginDetails";
SqlCommand CMD = new SqlCommand(CmdString, CON);
SqlDataAdapter SDA = new SqlDataAdapter(CMD);
DataTable DT = new DataTable("Main.tblEmployeeLoginIDetails");
SDA.Fill(DT);
lvDisplayEmployeeInformation.ItemsSource = DT.DefaultView;
}
}
My SelectionChanged Event for my ListView:
private void lvDisplayEmployeeInformation_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedRow = lvDisplayEmployeeInformation.SelectedIndex;
if (selectedRow != -1)
{
DataView DS = (DataView)lvDisplayEmployeeInformation.ItemsSource;
string ColumnEmailAddress = DS.Table.Rows[selectedRow].ItemArray[0].ToString();
string ColumnPassword = DS.Table.Rows[selectedRow].ItemArray[1].ToString();
string ColumnDepartment = DS.Table.Rows[selectedRow].ItemArray[2].ToString();
string ColumnIDNumber = DS.Table.Rows[selectedRow].ItemArray[3].ToString();
string ColumnName = DS.Table.Rows[selectedRow].ItemArray[4].ToString();
string ColumnSurname = DS.Table.Rows[selectedRow].ItemArray[5].ToString();
string ColumnGender = DS.Table.Rows[selectedRow].ItemArray[6].ToString();
string ColumnDOB = DS.Table.Rows[selectedRow].ItemArray[7].ToString();
string ColumnHomeAddress = DS.Table.Rows[selectedRow].ItemArray[8].ToString();
string ColumnTelephoneNumber = DS.Table.Rows[selectedRow].ItemArray[9].ToString();
string ColumnCity = DS.Table.Rows[selectedRow].ItemArray[10].ToString();
string ColumnProvinceCode = DS.Table.Rows[selectedRow].ItemArray[11].ToString();
string ColumnProfilePicture = DS.Table.Rows[selectedRow].ItemArray[12].ToString();
txtEmailAddress.Text = ColumnEmailAddress;
pbPassword.Password = ColumnPassword;
txtDepartment.Text = ColumnDepartment;
txtIDNumber.Text = ColumnIDNumber;
txtName.Text = ColumnName;
txtSurname.Text = ColumnSurname;
txtGender.Text = ColumnGender;
txtDOB.Text = ColumnDOB;
txtHomeAddress.Text = ColumnHomeAddress;
txtTelephoneNumber.Text = ColumnTelephoneNumber;
txtCity.Text = ColumnCity;
txtProvinceCode.Text = ColumnProvinceCode;
imgProfilePicture.Source = _img;
And lastly this is the coding I want use to convert/insert and retrieve my image into and from my database:
private void SetImage(Binary data)
{
if (data == null)
{
imgProfilePicture.BeginInit();
imgProfilePicture.Source = null;
imgProfilePicture.EndInit();
return;
}
_img = new BitmapImage();
_img.BeginInit();
_img.StreamSource = new MemoryStream(data.ToArray());
_img.EndInit();
imgProfilePicture.BeginInit();
imgProfilePicture.Source = _img;
imgProfilePicture.EndInit();
}
private Binary GetImageBinary()
{
if (imgProfilePicture.Source == null)
return null;
Stream stream = _img.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.CanRead && stream.Length > 0)
{
//Die Binary reader return 'n empty byte array :(
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((int)stream.Length);
}
}
return new Binary(buffer);
}
I can already insert the text form the database to my textboxes once I click on a row in my listview. Any Ideas?
EDIT: The error I get is as follows - " No imaging component suitable to complete this operation was found."
I have the following code which populates the Topic dropdownlist and saves it to a cached table:
bookingData2 = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query2 = #"Select * from [DB].dbo.[top]";// columng #1 = Specialty and column #2 = Topic
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query2, conn);
SqlDataAdapter da = new SqlDataAdapter(query2, conn);
da.Fill(bookingData2);
HttpContext.Current.Cache["cachedtable2"] = bookingData2;
bookingData2.DefaultView.Sort = "Topic ASC";
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
I have the following code which populates the Specialty dropdownlist and saves it to another cached table:
bookingData = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query = #"select * from [DB].dbo.[SP]";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(query, conn);
da.Fill(bookingData);
bookingData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = bookingData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
Specialty.Items.Remove("All Specialties");
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
How can I code the Specialty dropdownlist index change to do the following and save it to a cache table for quick access:
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
--> Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
}
Save bookingData2 table in ViewState or Session (I won't recommend to use session though) if it's not too heavy. Otherwise, its better you cache it or query the database again to repopulate it.
Let's assume you save bookingData2 in ViewState as follows in Page_Load
ViewState["bookingData2"] = bookingData2; // This should be before the following line
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic");
Then in your SelectedIndexChanged event do something like this
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
// Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
DataTable bookingData2 = (DataTable)ViewState["bookingData2"];
Topic.DataSource = bookingData2.Where(i => i.Specialty == "All Specialties" || i.Specialty == Specialty.SelectedValue).DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
}
Update - With Cached object
Do following in Specialty_SelectedIndexChanged event instead of where we used ViewState before.
if (HttpRuntime.Current.Cache["cachedtable2"] != null)
{
DataTable bookingData2 = HttpRuntime.Current.Cache["cachedtable2"] as DataTable;
// Rest of the code
}
I haven't tried this code. Let me know if you find any issues.
This is what solved it for me:
protected void Topic_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (Topic.SelectedIndex == 0)
{
string query = #"Specialty LIKE '%%'";
DataTable cacheTable = HttpContext.Current.Cache["cachedtable"] as DataTable;
DataTable filteredData = cacheTable.Select(query).CopyToDataTable<DataRow>();
filteredData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = filteredData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
else
{
string qpopulate = #"[Topic] = '" + Topic.SelectedItem.Value + "' or [Topic] = 'All Topics'"; //#"Select * from [DB].dbo.[table2] where [Specialty] = '" + Specialty.SelectedItem.Value + "' or [Specialty] = 'All Specialties'";
DataTable cTable = HttpContext.Current.Cache["cachedtable2"] as DataTable;
DataTable fData = cTable.Select(qpopulate).CopyToDataTable<DataRow>();
if (fData.Rows.Count > 0)
{
fData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = fData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
}
}
catch (Exception ce)
{
string error = ce.Message;
}
}
I'm trying to implement date-picker functionality in my project, but I can't do it quite right. I'm trying to pass the date-picker value in my oracle string so that it will compare with my db column and return results on the date criteria...
Whenever I pass it to the select statement it won't generate errors particularly but on button click it doesn't perform anything except it shows "not connected".
str = "Select * from sania.doctor where APPOINTMENT_DATE = "+ datepicker1.value;
It is clear it is logical mistake but I'm new to this C# concepts I need someone to tell me how to pass it and then display the results as well.
private void button1_Click(object sender, EventArgs e)
try
{
OracleCommand com;
OracleDataAdapter oda;
string ConString = "Data Source=XE;User Id=system;Password=sania;";
OracleConnection con = new OracleConnection(ConString);
{
// string id = dateTimePicker1.Text.Trim();
con.Open();
// str = "Select * from sania.doctor where APPOINTMENT_DATE = " + dateTimePicker1.value;
str = "select * from sania.doctor where APPOINTMENT_DATE to_date('"+dateTimePicker1.Value.ToString("yyyyMMdd") + "', 'yyyymmdd')";
com = new OracleCommand(str);
oda = new OracleDataAdapter(com.CommandText, con);
dt = new DataTable();
oda.Fill(dt);
Rowcount = dt.Rows.Count;
//int val = 0;
for (int i = 0; i < Rowcount; i++)
{
dt.Rows[i]["APPOINTMENT_DATE"].ToString();
//if (id == dateTimePicker1.Value)// this LINE SHOWS ERROR--because it is a string and I am using date with it. Don't know conversion
// {
// val = 1;
//}
}
// if (val == 0)
// { MessageBox.Show("INVALID ID"); }
// else
// {
DataSet ds = new DataSet();
oda.Fill(ds);
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
else { MessageBox.Show("NO RECORDS FOUND"); }
}
}
//}
catch (Exception)
{ MessageBox.Show("not connected"); }
}
Do not put values into SQL directly, use bind variables/parametes instead. For Oracle:
// :prm_Appointment_Date bind variable declared within the query
String str =
#"select *
from sania.doctor
where Appointment_Date = :prm_Appointment_Date";
....
using(OracleCommand q = new OracleCommand(MyConnection)) {
q.CommandText = str;
// datepicker1.Value passed into :prm_Appointment_Date via parameter
q.Parameters.Add(":prm_Appointment_Date", datepicker1.Value);
...
}
Doing like that you can be safe from either SQL Injection or Format/Culture differences
there is the code for loading image from database and shows it in picture box. the problem is if there's no pic in a row it will encounter an error however i marked as allow nulls image column in database.
private void button1_Click(object sender, EventArgs e)
{
sql = new SqlConnection(#"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True");
cmd = new SqlCommand();
cmd.Connection = sql;
cmd.CommandText = ("select Image from Entry where EntryID =#EntryID");
cmd.Parameters.AddWithValue("#EntryID", Convert.ToInt32(textBox1.Text));
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Images");
int count = ds.Tables["Images"].Rows.Count;
if (count > 0)
{
var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);
var stream = new MemoryStream(data);
pictureBox1.Image= Image.FromStream(sream);
}
}
you should check for DbNull.Value.
This should do the trick:
if (count > 0)
{
if (ds.Tables["Images"].Rows[count - 1]["Image"] != DbNull.Value){
var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);
(MemoryStreamstream = new MemoryStream(data)
pictureBox1.Image= Image.FromStream(sream);
}
}
You marked column id DB to accept null value so DB handles it but you also need do handle null in your application (you cannot cast DbNull value).
Hint
While using any kind of Stream you should use Using statement to dispose Stream after usage.
FYI, you need to learn to use using blocks. This will ensure that the objects are Disposed of in a timely manner, even if an exception is thrown:
private void button1_Click(object sender, EventArgs e)
{
var ds = new DataSet();
using (
var sql =
new SqlConnection(
#"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True")
)
{
using (
var cmd = new SqlCommand
{
Connection = sql,
CommandText =
"select Image from Entry where EntryID = #EntryID"
})
{
cmd.Parameters.AddWithValue(
"#EntryID",
Convert.ToInt32(textBox1.Text));
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(ds, "Images");
}
}
}
var imagesTable = ds.Tables["Images"];
var imagesRows = imagesTable.Rows;
var count = imagesRows.Count;
if (count <= 0)
return;
var imageColumnValue =
imagesRows[count - 1]["Image"];
if (imageColumnValue == DBNull.Value)
return;
var data = (Byte[]) imageColumnValue;
using (var stream = new MemoryStream(data))
{
pictureBox1.Image = Image.FromStream(stream);
}
}
just check
if(ds.Tables["Images"].Rows[count - 1]["Image"]!=DbNull.Value)
{
//you code of execution
}
else
{
//display default image
}