Listbox and SqlDataReader Issue - winforms

I am attempting load employee data from a stored procedure into a listbox in a form load event by ID and assign each with an image. The code above is what I have thus far. So what I'm trying to do here is to fill the listview with data from my data reader.
SqlConnection conn = new SqlConnection(
#"Data Source=MyPC\Test;Initial Catalog=TEST5;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT emp_first_name FROM Employees", conn);
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
listView1.Items.Clear();
while (dr.Read())
{
ListViewItem recs = new ListViewItem();
recs.Text = dr["dept_name"].ToString();
recs.Text = dr["emp_first_name"].ToString();
recs.Text = dr["emp_last_name"].ToString();
recs.Text = dr["emp_email"].ToString();
recs.Text = dr["emp_phone"].ToString();
recs.Text = dr["emp_position"].ToString();
recs.Text = dr["emp_address1"].ToString();
recs.Text = dr["emp_address2"].ToString();
recs.Text = dr["emp_city"].ToString();
recs.Text = dr["emp_state"].ToString();
recs.Text = dr["emp_postal_code"].ToString();
recs.Tag = dr["empId"].ToString();
recs.ImageIndex = 0;
listView1.Items.Add(recs);
}
Thank you in advance.

Your query is currently only returning one fieid:
SqlCommand cmd = new SqlCommand("SELECT emp_first_name FROM Employees", conn);
I'm guessing you wanted this:
SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn);
You need to open the connection and close your disposable resources. Your current code is constantly replacing the recs.Text property to the point that the only thing you should see in the list are "emp_postal_code" values. I suspect you are looking for something like this, where you display the user name as the main item of the ListViewItem and then include the other information as SubItems of the item (for when displaying in Detailed view):
listView1.Items.Clear();
using (SqlConnection conn = new SqlConnection(...)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn)) {
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read()) {
ListViewItem recs = new ListViewItem();
recs.Text = dr["emp_first_name"].ToString() + " " +
dr["emp_last_name"].ToString();
recs.SubItems.Add(dr["dept_name"].ToString());
recs.SubItems.Add(dr["emp_email"].ToString());
etc...
recs.Tag = dr["empId"].ToString();
recs.ImageIndex = 0;
listView1.Items.Add(recs);
}
}
}
}

I see several things here:
You never open the connection:
You reference a number of fields in the reader that are not included in your statement's select clause.
You overwrite, rather than append to, the text property of your ListViewItem, so that only the last assigned property value will show.

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.

how to excel to datagridview ,it's empty

(button1)
OpenFileDialog OpenFile = new OpenFileDialog();
if (OpenFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
textBox_path.Text = OpenFile.FileName;
(button2)
string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" +
textBox_path.Text +"; Extended Properties =\"Excel 8.0;HDR=NO;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + textBox_SheetName.Text + "$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
My question is
I import data of excel to datagridview ,and then it was only increase a empty row. please help me.

ADO.Net Get Inserted Row's ROW ID without designer wizard

I have a generic update function that takes a datatable, select query and uses this to update the database tables.It is working fine. I need to know is there a way to get back the inserted row's ID (identity field) by changing something in the below code.
Public Function UpdateDataTable_GetID(ByVal dt As DataTable, ByVal SQL As String, ByVal connString As String) As Integer
Dim conn As SqlConnection = Nothing
Dim cmd As SqlCommand
Dim adp As SqlDataAdapter = Nothing
Dim cmdBuilder As SqlCommandBuilder = Nothing
Dim UpdatedID As Integer
If SQL.Length <= 0 Then
Return False
End If
conn = New Data.SqlClient.SqlConnection(connString)
cmd = New Data.SqlClient.SqlCommand
cmd.Connection = conn
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
adp = New Data.SqlClient.SqlDataAdapter(cmd)
cmdBuilder = New Data.SqlClient.SqlCommandBuilder(adp)
Try
UpdatedID = Convert.ToInt32(adp.Update(dt)) ' What to do here to get the just inserted ID instead of number of records updated
adp.Dispose()
cmdBuilder.Dispose()
Return UpdatedID
Catch ex As System.Data.SqlClient.SqlException
' Closing connection
Return -1
Finally
End try
End function
I am aware of solutions wherein I can append "select scope_identity()" to the insert Command of data adapter's query using designer as well as editing the adapter's insertcommand text and then doing an ExecuteScalar(). I want to know if the generic adapter.Update() can be tweaked to get the inserted row's ID.
you can subscribe to this event in code like this : (C# I dont know VB)
adp.RowUpdated += adapter_RowUpdated;
and write the event yourself :
void adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
if (e.StatementType == StatementType.Insert)
{
object id = e.Command.Parameters["#ID"].Value;
e.Row[_identityFieldName] = id;
}
}
In this example the following has been added to the commandtext first :
SET #ID = SCOPE_IDENTITY()
and a private variable _identityFieldName has been filled.
Maybe this can help you.
EDIT: I noticed you also use an SqlCommandBuilder that makes things easier to add the Scope identity :
SqlCommand inserter = new SqlCommand();
inserter = cmdBuilder.GetInsertCommand(true).Clone();
inserter.CommandText += " SET #ID = SCOPE_IDENTITY()";
SqlParameter param = new SqlParameter();
param.Direction = ParameterDirection.Output;
param.Size = 4;
param.DbType = DbType.Int32;
param.ParameterName = "#ID";
inserter.Parameters.Add(param);
adp.InsertCommand = inserter;

Read data from SQL Server database with c#

I have list of BuilderString which I want to contain data
public List<int> IDS = new List<int>();
public List<StringBuilder> Items = new List<StringBuilder>();
What's wrong with this code?
SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True");
SqlDataReader rdr2;
SqlCommand cmd2;
con2.Open();
for (int i = 0; i < IDS.Count; i++)
{
cmd2 = new SqlCommand("select item From TransactiontData where idT=#IDS[i]", con2);
cmd2.CommandType = CommandType.Text;
rdr2 = cmd2.ExecuteReader();
SqlParameter param = new SqlParameter();
param.ParameterName = "#IDS[i]"
while (rdr2.Read())
{
Items[i].Append((StringBuilder)rdr2["item"]);
}
}
You need to rearrange your code a bit:
using (SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True"))
using (SqlCommand cmd2 = new SqlCommand("select item From TransactiontData where idT = #IDS", con2))
{
// add the paramter to the command
cmd2.Parameter.Add("#IDS", SqlDbType.Int);
con2.Open();
for (int i = 0; i < IDS.Count; i++)
{
// set the parameter value
cmd2.Parameter["#IDS"].Value = IDS[i];
// only *THEN* call ExecuteReader()
using (SqlDataReader rdr2 = cmd2.ExecuteReader())
{
while (rdr2.Read())
{
// **NOT SURE** what you're trying to do here.....
// First of all, you need to just call Items.Add()
// to add new items to the list - and I'm TOTALLY
// UNCLEAR what you're trying to do casting the reader
// value to a StringBuilder.......
//
// Items[i].Append((StringBuilder)rdr2["item"]);
//
// replaced with what *might* make more sense.....
Items.Add(rdr2["item"].ToString());
}
rdr.Close();
}
}
con2.Close();
}
Points to note:
I would recommend to always put your SqlConnection, SqlCommand and SqlDataReader into using() {...} blocks to ensure proper disposal
you need to add your parameter and set its value BEFORE you call .ExecuteReader()!
Since the query itself never changes - there's no point in creating a new SqlCommand on every iteration. Create the command once - and then just set the parameter value (which is the only thing changing) once per iteration
You need to assign the parameter value in the application code rather than within the query. I'm not sure exactly what you are trying to accomplish by casting the column value as a StringBuilder. Assuming that each StringBuilder item is to contain a single string retrieved from a varchar/nvarchar column, the example below will do that.
for (int i = 0; i < IDS.Count; i++)
{
var cmd2 = new SqlCommand("select item From TransactiontData where idT=#IDS", con2);
SqlParameter param = new SqlParameter("#IDS", SqlDbType.Int) { Value = IDS[i] };
var rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
Items.Add(new StringBuilder((string)rdr2["item"]));
}
}

sqldatabase variable declaration from a listbox in Vb.net 2010

I'm trying to save the selected Item from the listbox to the database but when i choose the item from the listbox I get a Runtime error that the variable(RomID) is not declared. Here's the code. What am I missing?!
If (con.State = ConnectionState.Closed) Then
con.Open()
End If
Dim Name As SqlParameter = New SqlParameter("#Name", TxtName.Text)
Dim Pass As SqlParameter = New SqlParameter("#PassportNum", TxtPassNum.Text)
Dim Mobile As SqlParameter = New SqlParameter("#PhoneNUm", TxtMobile.Text)
Dim RomID As SqlParameter = New SqlParameter("#ID", Integer.Parse(ListBox1.SelectedItem))
Dim ChckIn As SqlParameter = New SqlParameter("#CheckIndate", DateTime.Now.Date)
Dim Email As SqlParameter = New SqlParameter("#Email", TxtEmail.Text)
Cmd.Parameters.Add(Name)
Cmd.Parameters.Add(Pass)
Cmd.Parameters.Add(Mobile)
Cmd.Parameters.Add(RomID)
Cmd.Parameters.Add(ChckIn)
Cmd.Parameters.Add(Email)
Cmd.CommandText = "Update Rooms set Status ='Booked' where ID = #RomID"
Cmd.ExecuteNonQuery()
Cmd.CommandText = "insert into Reservation(RoomID,GuestName,PassportNum,PhoneNUm,CHeckIndate,Email) VALUES(#RomID,#Name,#Pass,#Mobile,#ChckIn,#Email)"
Cmd.ExecuteNonQuery()
MessageBox.Show("Reservation Was Successful")
I have not declared in the same way can you try this:
remove:
Dim RomID As SqlParameter =
New SqlParameter("#ID", Integer.Parse(ListBox1.SelectedItem))
try something like this :
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = Integer.Parse(ListBox1.SelectedItem)
You have this:
Dim RomID As SqlParameter =
New SqlParameter("#ID", Integer.Parse(ListBox1.SelectedItem))
I think you meant this:
Dim RomID As SqlParameter =
New SqlParameter("#RomID", Integer.Parse(ListBox1.SelectedItem))

Resources