Populate stored procedure result to a List<T> - c#

Is there a way to map the results of a stored procedure to a generic list instead of a dataset/datatable?
Currently I follow these steps:
Execute stored procedure
Take the result in Dataset
Populate list from the Dataset.
Is there a way to eliminate step (2).
OleDbCommand cm = new OleDbCommand();
cm.Connection = AccessConnection();
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "seltblContacts";
OleDbDataAdapter adp = new OleDbDataAdapter(cm);
DataTable dt = new DataTable();
adp.Fill(dt);
List<tblContacts> LstFile = new List<tblContacts>();
if (dt.Rows.Count > 0)
{
tblContacts t;
foreach (DataRow dr in dt.Rows)
{
t = PopulateContacts(dr);
LstFile.Add(t);
}
}

Yes of course you can do that - just execute your command and get back a reader, and then iterate over the rows in the result set and build up your objects:
using (OleDbCommand cm = new OleDbCommand())
{
cm.Connection = AccessConnection();
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "seltblContacts";
List<tblContacts> LstFile = new List<tblContacts>();
using (OleDbReader reader = cm.ExecuteReader())
{
while(reader.Read())
{
tblContacts contact = new tblContacts();
// here, set the properties based on your columns from the database
contact.FirstName = reader.GetString(0);
contact.LastName = reader.GetString(1);
// etc.
LstFile.Add(contact);
}
reader.Close();
}
return LstFile;
}
For details on OleDbReader and how to use it, see this other SO question or find tons of tutorials and samples online using Bing or Google.

Related

SQL Server distinct connection to database in C#

I am trying to drop down box in design but in database table category has duplicates. I tried to execute by using below code. But it is not executing. It just receiving all commands which I have been changes in properties:
cmd.CommandText = #"Select Distinct Category_Desc from
Database***name order
by Category_Desc";
adapter.SelectCommand = cmd;
SqlDataReader dr1 = cmd.ExecuteReader();
dr1.Read();
comboBoxCategory.ValueMember = "Category_Desc";
comboBoxCategory.DisplayMember = "Category_Desc";
comboBoxCategory.DataSource = dr1;
dr1.Dispose();
Can anyone please help how to execute distinct query from the code?
Data reader is a forward only cursor that you have to iterate and close after the last item.Look at this code segment
SqlDataReader dr1= command.ExecuteReader();
ArrayList arl= new ArrayList();
while (dr1.Read())
{
arl.Add(dr1("Category_Desc"));
}
dr1.close();
//If its a winform project use this
string [] str = al.ToArray(typeof(string));
FarPoint.Win.Spread.ComboBoxCellType cb = new
FarPoint.Win.Spread.ComboBoxCellType();
cb.Items = arl;
Use the adapter to fill a DataTable instead. You already have the adapter and it already has the SelectCommand assigned.
adapter.SelectCommand = cmd;
System.Data.DataTable dtCategories = new System.Data.DataTable();
adapter.Fill(dtCategories);
comboBoxCategory.ValueMember = "Category_Desc";
comboBoxCategory.DisplayMember = "Category_Desc";
comboBoxCategory.DataSource = dtCategories;

retrieve with multi or

im creating wfp application i want to retrieve table to datagridview
with multi value selected in listbox, getting all data that selected from listbox, so the main idea
is apply this query from sql to application
select * from Vwtb where firstname='' or firstaname='' or ..
i have tried with while loop and searched a lot but not worked this is my code please if its something strange for you im not professional :)
string[] orand = { "or"+listBox1.Text };
foreach (string sm in orand)
{
cn.Open();
string select = "select * from productvw where firstname='" + sm + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
}
any type of help will be so appreciated ....
You can convert your array to a string that can be used in IN operator.for achieving that, use this extension method
public static class StaticClass
{
public static string ConvertStringArrayToString(this string[] array)
{
StringBuilder builder = new StringBuilder();
for (int i=0;i<array.Length;i++)
{
builder.Append(array[i]);
if(i+1==array.Length)break;
builder.Append(',');
}
return builder.ToString();
}
}
Then in your code use it like this
string[] orand = { "or"+listBox1.Text };
var values=orand.ConvertStringArrayToString();
cn.Open();
string select =" SELECT * FROM productvw WHERE firstname IN "+"("+values+")"
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
You could use the IN operator.
string command = "SELECT * FROM productvw WHERE firstname IN (#names)";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
dataAdapter.Parameters.Add("#names", names);
The names would be a list of strings, List<string>, and would contain all the first names you want to use.
You can use the following syntax:
SELECT *
FROM productvw
WHERE firstname IN (value1,value2,...);
Start by creating a loop that generates the sql string With the values populated.

DataAdapter Update issue

The following coding doesn't update my table. But rows variable value is 1 after updating.
I cannot understand what is the cause behind this. Please help.
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
var wktbl = new DataTable();
var cmd = new SqlCommand("SELECT * FROM Test", connection1);
var da1 = new SqlDataAdapter(cmd);
var b = new SqlCommandBuilder(da1);
da1.Fill(wktbl);
wktbl.Rows[0][2] = "5";
da1.UpdateCommand = b.GetUpdateCommand(true);
int rows = da1.Update(wktbl);
Check this page out. It shows the example below of doing an update with the dataadapter.
The following examples demonstrate how to perform updates to modified rows by explicitly setting the UpdateCommand of a DataAdapter and calling its Update method. Notice that the parameter specified in the WHERE clause of the UPDATE statement is set to use the Original value of the SourceColumn. This is important, because the Current value may have been modified and may not match the value in the data source. The Original value is the value that was used to populate the DataTable from the data source.
private static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT CategoryID, CategoryName FROM Categories",
connection);
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID", connection);
dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryID", SqlDbType.Int);
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;
DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);
DataRow categoryRow = categoryTable.Rows[0];
categoryRow["CategoryName"] = "New Beverages";
dataAdpater.Update(categoryTable);
Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}
I found the problem. It's because connectionString has |DataDirectory|.
The MDF file location is different when running the application.

Drop down list not binding with sqldatareader

i have a form with a collection of about five drop down . i have my query as follows .
string sql = "SELECT a.clientID ,a.[cname],b.bid,b.[bname],c.contactID, c.[name] FROM "
+ " dbo.[CLIENT] AS a INNER JOIN dbo.[BRANCH] AS b "
+ "ON a.clientID = b.clientID JOIN dbo.[CONTACT] AS "
+ " c ON b.bid = c.bid ORDER BY a.clientID ";
i then followed and bind my drop down individually to their respective columns as follows.
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
drClient.Enabled = true;
drClient.DataSource = reader;
drClient.DataTextField = "cname";
drClient.DataValueField = "clientID";
drClient.DataBind();
drBranch.Enabled = true;
drBranch.DataSource = reader;
drBranch.DataTextField = "bname";
drBranch.DataValueField = "bid";
drBranch.DataBind();
drContact.Enabled = true;
drContact.DataSource = reader;
drContact.DataTextField = "name";
drContact.DataValueField = "contactID";
drContact.DataBind();
drEmail.Enabled = true;
drEmail.DataSource = reader;
drEmail.DataTextField = "name";
drEmail.DataValueField = "contactID";
drEmail.DataBind();
drFax.Enabled = true;
drFax.DataSource = reader;
drFax.DataValueField = "contactID";
drFax.DataTextField = "name";
drFax.DataBind();
when i run this, only the first drop down bind successfully. The rest don't. I also try to loop through the reader by adding
while(reader.read())
{
then my bindings
}
the above also fails. I though of looping as below as well.
while(read.HasRows)
{
}
it still fails. I am confused,any help would be appreciated. thanks
Reader is readonly and forward only that's why only first dropdonw get filled with data and others are empty.
You can use datset or Datatable for same problem .
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
Dataset dsresult = cmd.ExecuteDataset();
If(dsResult !=null)
{
if(dsResult.Rows.count>0)
{
drClient.Enabled = true;
drClient.DataSource = dsResult.Tables[0] ;
drClient.DataTextField = Convert.ToString(ds.Tables[0].Columns["cname"]);
drClient.DataValueField = ds.Tables[0].Columns["clientID"] ;
drClient.DataBind();
}
}
Datareader is connected architecture needs continuous connection and fetches one row at a time in forward mode better use dataset which uses disconnected architecture and can be used for retrieving data multiple times.
This seems clear postback problem.
Bind your drop down on !postback.
Eg.
if(!IsPostBack)
{
populateDdl();
}
Either you will have to make a seperate reader for each binding
or you can do this by filling a datatable ( i would prefer this). Like,
DataTable dt = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(sql, connection))
{
a.Fill(dt);
}
drClient.DataSource = dt;
drClient.DataBind();
drBranch.DataSource = dt;
drBranch.DataBind();
drContact.DataSource = dt;
drContact.DataBind();
drFax.DataSource = dt;
drFax.DataBind();
Your choices are to either rerun/refill it or create separate readers or better yet fill a datatable instead and then you can reuse the datatable.

connect and read .MDB item with C#

Is it possible to connect to a local MDB file and pick a single bit of info out of it ?
I have a table in a .mbd file with a single bit of info in it. I would like to have that record be output into a disabled textbox for a reference. I believe I can get the DB open, and run the query but no idea what I need to read from it.
thanks
var myDataTable = new DataTable();
using (var conection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=C:\\menus\\newmenus\\menu.mdb;Password=****"))
{
conection.Open();
var query = "Select siteid From n_user";
var adapter = new OleDbDataAdapter(query, conection);
OleDbCommandBuilder oleDbCommandBuilder = new OleDbCommandBuilder(adapter);
}
To simply read a single field on your database table you could use an OleDbDataReader that could loop over the result and return the field required..
var myDataTable = new DataTable();
using (var conection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=C:\\menus\\newmenus\\menu.mdb;Password=****"))
{
conection.Open();
var query = "Select siteid From n_user";
var command = new OleDbCommand(query, conection);
var reader = command.ExecuteReader();
while(reader.Read())
textBox1.Text = reader[0].ToString();
}
if you have just one record and just one field then a better solution is the method ExecuteScalar
conection.Open();
// A query that returns just one record composed of just one field
var query = "Select siteid From n_user where userid=1";
var command = new OleDbCommand(query, conection);
int result = (int)command.ExecuteScalar(); // Supposing that siteid is an integer
Probably I should also mention that ExecuteScalar returns null if the query doesn't find a match for the userid, so it is better to be careful with the conversion here
object result = command.ExecuteScalar();
if( result != null)
int userID = (int)result;
.....
Yes very possible. Just have the adapter fill the DataTable, also I don't think you'll need the OleDbCommandBuilder.
using (var conection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=C:\\menus\\newmenus\\menu.mdb;Password=****"))
{
conection.Open();
var query = "Select siteid From n_user";
var adapter = new OleDbDataAdapter(query, conection);
adapter.Fill(myDataTable);
myTextBox.Text = myDataTable.Rows[0][0].ToString();
}
Also I think using ExecuteScalar would be a better solution, but my answer was tailored to the objects you had already instantiated.
You could use OleDbCommand.ExecuteScalar to retrieve a single value. It is returned as an object and you could cast it to the correct type.
Are you looking for stm like this?
OleDbCommand cmd = new OleDbCommand();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
// read ur stuff here.
}

Categories