Find data in data set - database

I've googled this found a few useful sites that have helped me out but not sure exactly what is going wrong. I have my database with data in it. I can display data on the page load and I can sort through the data with next and previous buttons, but the issue is my find button is not working and always display my "no rows found" message when searching for a name. I'm sure there is a more efficient way to do this but havent looked in to that just yet.
Thanks
Here is my code:
string searchFor = txtSearch.Text.Trim();
int results = 0;
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\AddressBook.mdb");
conn.Open();
DataSet ds = new DataSet();
string cmd = "SELECT * FROM tblAddressBook";
OleDbDataAdapter da = new OleDbDataAdapter(cmd, conn);
da.Fill(ds, "Info");
DataRow[] returedRows;
DataRow dr;
returedRows = ds.Tables.Select("LastName=' " + searchFor + " ' ");
results = returedRows.Length;
if (results > 0)
{
dr = returedRows[0];
txtFirstName.Text = dr["FirstName"].ToString();
txtLastName.Text = dr["LastName"].ToString();
txtEmail.Text = dr["Email"].ToString();
txtPhone.Text = dr["PhoneNumber"].ToString();
}
else
{
lblReturned.Text = "No Rows Found";
}
//close the connection
conn.Close();

Your .Select string is adding a space to the beginning and end of the search term. If searchFor contained Thompson then your statement would be
.Select("LastName=' Thompson ' ")
so no entries would match unless they had a leading space. Also, I had no idea what ds.tblAddressBook had to do with anything so I just used this instead:
returedRows = ds.Tables["Info"].Select("LastName='" + searchFor + "'");
Now you need to tweak your code so it won't blow up when somebody tries to search for O'Connor.

Related

No value given for one or more required parameters.What is error in query

if (conn.State == ConnectionState.Closed) { conn.Open(); }
string sql = "SELECT debit.tblgltransactions AS Debit,credit.tblgltransactions AS Credit,glaccounttype.tblglaccounttypes from tblgltransactions,tblglaccounttypes where glaccounttype.tblglaccounttypes='" + cmbGeneralLedgerAccounts + "'and transactiondate.tblgltransactions='"+dtpFromDate+"'AND '"+dtpToDate+"'";
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
oda.Fill(dt);
dgvGeneralLedger.DataSource = dt.DefaultView;
if (conn.State == ConnectionState.Open) { conn.Close(); }
Maybe you missed a space in front of those "AND" statements?
And as far as I can see you are referring to transactiondate table without declaring it in from or a join statement.
EDIT:
You dont referrence both of the tables in the where condition. Dont know how that should work.

Deleting from Database

I wrote a method to delete values from a database, however when I check the rows affected the value is 0 and keeps going into the first if statement any ideas?
private void workstationDelete()
{
string query = "DELETE FROM test_revision2 where wsid = #wsid and location = '#location'";
try
{
conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#wsid", Convert.ToInt32(wsid2text.Text));
cmd.Parameters.AddWithValue("#location", deletelocation);
cmd.ExecuteNonQuery();
int rowsaffected = cmd.ExecuteNonQuery();
if (rowsaffected == 0)
{
lblDel.Text = "Sorry Workstation: " + wsid2text.Text + " does not exist in " + deletelocation + ". Therefore it cannot be removed.";
}
else
{
lblDel.Text = "You have successfully removed Workstation: " + Convert.ToInt32(wsid2text.Text) + " in " + deletelocation;
}
conn.Close();
}
catch (SqlException)
{
lblDel.Text = "randome";
}
}
Remove the single quotation marks from '#location'. You have it ignoring the parameter and trying to match a string literal.
Aside: There are good reasons not to use AddWithValue.
The problem was I was using cmd.executeNonQuery twice the first one was returning 1 however when I initialized to a var it becomes 0. Use execute non query once - when assigning the int var.

Reload a Datagrid View returns Nothing

I have the a Function that loads data into from a Microsoft Access DB into a DGV as shown in code below:
Public Sub LoaddgvCombined()
Try
'//Clear DataGrid
ds.Clear()
dgvSales.DataSource = Nothing
'dgvSales.Refresh()
dgvSales.DataSource = ds
'//Establish Connection to DB
con.ConnectionString = dbProvider & dbSource
tables = ds.Tables
con.Open()
sql = "SELECT * FROM [tblINV_SalesRecord] WHERE CDate(adddate & ' ' &addtime) < CDate('" & selectfrm & "')) ORDER BY temID ASC"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "tblINV_SalesRecord")
con.Close()
Dim view As New DataView(tables(0))
source1.DataSource = view
dgvSales.DataSource = view
dgvSales.AllowUserToAddRows = False
If dgvSales.RowCount < 1 Then
MessageBox.Show("No Sales Recorded Found From " & selectfrm)
End If
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
MessageBox.Show("An Error Occured While Loading Sales Record ")
End Try
End Sub
It works fine the first time, but when I call the function the second time it empties the DGV but this time it does not load any Data.
Please can anyone point out what I am doing wrong.
The thing I noticed here is that you are passing to tables BEFORE you are getting the result of your query.
Try passing the values for tables after you fill ds.
Like this:
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "tblINV_SalesRecord")
con.Close()
tables = ds.Tables '<=== transfer it here
It's showing empty because at the point you are passing to tables, your ds variable is not yet filled from your query.

How to display images from access attachment and list them in radgridview

I have the following code
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtFileLocation.Text;
using (DbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
DbCommand command = conn.CreateCommand();
string idfield = txtIDField.Text;
string picfield = txtPictureField.Text;
command.CommandText = "select " + idfield + ", " + picfield + " from " + selectedTable;
command.CommandType = CommandType.Text;
DbDataReader reader = command.ExecuteReader();
gridResults.DataSource = reader;
conn.Close();
}
The database is an access database as u might have seen from the connection string, also the database I was provided with store their images in the database, as Image attachment.
Whenever I load the grid it shows random stuff :(
eg.
I am not familiar with the wiring up of a database so this might be an easy question, how do I enable my picture list in my form?

insert and display image in vb.net from sql server database

i need to upload and display images to and from database. i have written this code for uploading and it uploads fine. except 1 problem. It crashes when i dont select an image. can someone help me fix it for null value? also how do you display an image in IE?
code for inserting image -
Dim imageInfo As FileInfo = Nothing
Dim data() As Byte = Nothing
imageInfo = New FileInfo(Me.UploadLogo.Value.Trim())
Dim imagestream As FileStream = New FileStream(imageInfo.ToString, FileMode.Open)
if name_id > 0
ReDim data(imagestream.Length - 1)
imagestream.Read(data, 0, imagestream.Length)
imagestream.Close()
Sqlstr = "UPDATE logos WITH(ROWLOCK) " & _
"SET Logo=#Logo,Modified_Date=GETDATE() " & _
"WHERE ID = " + name_id.ToString + ""
Else
Sqlstr = "INSERT logos (Logo,Created_Date) " & _
"VALUES ("#Logo,GETDATE())"
End If
SqlCmd = New SqlCommand(Sqlstr, SqlCnn)
Dim pictureParameter As SqlParameter = Nothing
pictureParameter = New SqlParameter("#Logo", SqlDbType.Image)
pictureParameter.Value = data
SqlCmd.Parameters.Add(pictureParameter)
SqlCmd.ExecuteScalar()
this works fine only if an image is selected, crashes for NULL values.
Also please help me with image display. thanks
To solve your "file not selected problem", you should have an If statement along the lines of:
If Not File.Exists(Me.UploadLogo.Value.Trim())
' Exit out or handle no file selected
End If

Resources