Dataset from database is empty - c#

I'm accessing a table from my database. I have added the tables as a dataset in Visual Studio 2013, but when I try to use it, it comes out empty.
This is what I'm trying to do:
IQueryable<NorthwindDataSet.OrdersRow> LookupOrdersForYear(int year)
{
using (var context = new NorthwindDataSet())
{
var orders =
from order in context.Orders
where order.OrderDate != null && order.OrderDate.Year >= year
select order;
return orders.ToList().AsQueryable();
}
}
I found out that orders was empty, so I added
Console.WriteLine(context.Orders.Count);
which gave me an output of 0. What went wrong?

I found out that I needed to fill my dataset with data, or it would stay empty.
A SqlDataAdapter did the trick:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand("SELECT * FROM Orders");
string connString = #"Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
adapter.SelectCommand = command;
adapter.SelectCommand.Connection = conn;
adapter.Fill(context.Orders);
There are several overloaded methods for SqlDataAdapter.Fill, of which one takes a dataset and another takes a datatable. When I first used the SqlDataAdapter, I used the one that takes a dataset
adapter.Fill(context);
which still gave me an empty context.Orders. The correct one takes a datatable:
adapter.Fill(context.Orders);
This one worked and returned the dates as expected.

Related

The DataSet result is always empty in C#

I am retrieving particular column value using DataSet.
This is my code:
public DataSet GetRedirectURL(string emailId)
{
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(#"Connection_String_Here"))
{
con.Open();
SqlCommand sqlComm = new SqlCommand("usp_Login", con)
{
CommandType = CommandType.StoredProcedure
};
sqlComm.Parameters.AddWithValue("#EmailId", emailId);
SqlDataAdapter da = new SqlDataAdapter
{
SelectCommand = sqlComm
};
da.Fill(ds);
}
return ds;
}
I have also used DataTable instead of it but the same result.
I have checked my Stored Procedure and when I pass Parameter it shows Data. So, nothing wrong with the SP. But the Table doesn't show any data and is always empty as shown below:
What am I missing? Any help would be appreciated.
I'd suggest you to first evaluate the content of your DataSet. For instance, type in your Immediate Window (or add a quick watch) to check ds.Tables[0].Rows.Count. Basically, to assert your DataSet has been properly filled with the contents fetched from the database, and focus on the data assignment from the DataSet to the grid object you're using to display it.
Also, the .Fill() method has a returning object which is an int representing the amount of rows that have been successfully filled into the target object. For instance:
int result = da.Fill(ds);
Check the value of result after the .Fill() method has been executed.
Finally, I guess you're using a DataGridView object to visualize the results. If so, how are you binding data? Should be something like:
dataGridView1.DataSource = ds.Tables[0];
PS: As I've read in other comments, no, you don't need to execute the .Open() method on the connection. That's not necesarry, it's done implicitely when using the (using SqlConnection conn = SqlConnection..)

Using CheckedListBox Values in SQL Select Statements

I have two CheckedListBoxes, Standard Codes and Standard Details. Upon initialization, Standard Codes is populated from a query to the database.
InitializeComponent();
SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Project;Integrated Security=True");
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter
("SELECT [StandardCode] FROM [dbo].[StandardCodesAndDetails]", conn);
adapter.Fill(ds);
this.lstBoxStandardCodes.DataSource = ds.Tables[0];
this.lstBoxStandardCodes.DisplayMember = "StandardCode";
conn.Close();
From this CheckedListBox, the user is able to select multiple Standard Code values. As these values are checked or unchecked, I want to run a query that will populate the Standard Details CheckedListBox with the related Standard Details from the database, with some Standard Codes having more than one Standard Detail. This is the part I'm not sure how to write. I'm not sure how to include checked CheckedListBox values in a SQL statement like this.
Any help at all would be appreciated. Thank you.
You have to create your sql statement dynamically instead of hard coding it.For example I will write a method which provide a sql statement based on user input like this.
public string CreateSQL(string userName,string password)
{
string sql="SELECT * FROM Table WHERE";
if(!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
sql+=" UserName='"+userName+"' AND Password='"+password+"'";
}
else if(!string.IsNullOrWhiteSpace(userName))
{
sql+=" UserName='"+userName+"'";
}
else if(!string.IsNullOrWhiteSpace(password))
{
sql+=" Password='"+password+"'";
}
else
{
sql=null;
}
return sql;
}

C# Fill combo box from SQL DataTable

DataTable _dt = new DataTable();
using (SqlConnection _cs = new SqlConnection("Data Source=COMNAME; Initial Catalog=DATABASE; Integrated Security=True"))
{
string _query = "SELECT * FROM Doctor";
SqlCommand _cmd = new SqlCommand(_query, _cs);
using (SqlDataAdapter _da = new SqlDataAdapter(_cmd))
{
_da.Fill(_dt);
}
}
cbDoctor.DataSource = _dt;
foreach(DataRow _dr in _dt.Rows)
{
cbDoctor.Items.Add(_dr["name"].ToString());
}
There was an Error...
The result is System.Data.DataRowView instead of data from database..
I'm not yet sure what is the exact error in your code, but if you're ok with not using DataTable, you can do it this way:
using (SqlConnection sqlConnection = new SqlConnection("connstring"))
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Doctor", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
cbDoctor.Items.Add(sqlReader["name"].ToString());
}
sqlReader.Close();
}
For more information take a look at SqlDataReader reference on MSDN.
In orer to find the issue in the original code you posted, please provide information in which line you get the exception (or is it an error that prevents application from compiling?) and what is its whole message.
You could also specify DisplayMember property of combobox to any of the column name.
For example if you want to display Name field, you could do
Combobox1.DisplayMember="Name";
I think the problem is that you are trying to insert multiple columns into a comboBox (which can accept only one column). Adjust your SELECT statement so that it combines all of the data you need into one column:
Example:
SELECT Name + ' ' LastName + ' '+ ID AS 'DoctorData' FROM Doctor
By using the + operator you can combine multiple columns from the database, and represent it as a single piece of data. I think that your code should work after that (you can even comment the foreach loop, I think that adding data source to your comboBox will be enough)

Combobox add rows dynamically and dropdown from SQL Server stored procedure

This is basically a search tool. When I type some thing in a combobox, the combobox drops down and will show me suggestions (something like Google search bar)
I created a procedure which does some complex calculations, which take one parameter and returns some rows. Then I created a combobox event (On Update Text).
And in the event handler I wrote this code:
private void combobox_TextUpdate(object sender, EventArgs e)
{
this.combobox.Items.Clear();
DataTable List = new DataTable();
if (this.combobox.Text.Length > 0)
{
List = searchIt(combobox.text);
foreach (DataRow Row in List.Rows)
{
this.combobox.Items.Add(Row.ItemArray.GetValue(0).ToString());
}
this.combobox.DroppedDown = true;
}
}
static public DataTable searchIt(string STR)
{
string connectionString = McFarlaneIndustriesPOSnamespace.Properties.Settings.Default.McFarlane_IndustriesConnectionString;
SqlConnection con = new SqlConnection(connectionString);
DataTable DT = new DataTable();
con.Open();
SqlDataAdapter DA = new SqlDataAdapter("USE [McFarlane Industries] " +
"EXEC search " +
STR, connectionString);
DA.Fill(DT);
con.Close();
return DT;
}
The function searchIt executes the stored procedure and it returns a DataTable. The stored procedure is working fine in SQL Server Management Studio.
But in the application it is not working correctly in some cases.
When I type [space], then it throws an exception and it says stored procedure needs parameter which is not provided.
There are many other characters when I type them it throws exception that invalid character at end of string "my string".
Any suggestion how could I achieve my goal.
Call your stored procedure with sqlcommand to fill your datatable
using (SqlConnection scn = new SqlConnection(connect)
{
SqlCommand spcmd = new SqlCommand("search", scn);
spcmd.Parameters.Add("#blah", SqlDbType.VarChar, -1); //or SqlDbType.NVarChar
spcmd.CommandType = System.Data.CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter(spcmd))
{
da.Fill(dt);
}
}
static public DataTable searchIt(string STR)
{
string connectionString = McFarlaneIndustriesPOSnamespace.Properties.Settings.Default.McFarlane_IndustriesConnectionString;
SqlConnection con = new SqlConnection(connectionString);
DataTable DT = new DataTable();
con.Open();
SqlCommand command = new SqlCommand("Name_of_Your_Stored_Procedure",con);
command.CommandType=CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#parameter_name",SqlDbType.NVarChar));
command.Parameters[0].Value="Your Value in this case STR";
SqlDataAdapter DA = new SqlDataAdapter(command);
DA.Fill(DT);
con.Close();
return DT;
}
Important :
'parameter_Name' and 'Name_of_Your_Stored_Procedure' should be replaced by yours which you have in database. And value of parameter could be like "abc" (combox.Text)
Command and its type, its text are necessary.
Adding parameters depends upon your stored procedure. They can be 0,1 or more but once they are added their values must be given. conn(connection) can be passed to new SqlCmmand() or new SqlDataAdapter()
No need of things like 'use' and 'exec'
Following me and this link might be helpful in future for stored procedures
http://www.codeproject.com/Articles/15403/Calling-Stored-procedures-in-ADO-NET
Two optional Suggestions for you
use variable name 'list' instead of 'List' (you used) however you will not get problem with this name until you add a namespace using System.Collections.Generic; but you may need to use this namespace in future.
Use only list.Rows[0].ToString(); no need to get itemarray then get value when you are working with data in strings;

how to print single value of data set

conn = new SqlConnection(#"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true");
ada = new SqlDataAdapter("select total_amount from debit_account where account_no=12", conn);
ds = new DataSet();
ada.Fill(ds);
Now, I want to print value of the dataset... how? Please help me.
I'd suggest that the best option here isn't actually a SqlDataAdapter and DataSet, but rather a SqlCommand. Try this:
using(SqlConnection conn = new SqlConnection(#"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true"))
{
conn.Open()
using (SqlCommand command = new SqlCommand("select total_amount from debit_account where account_no=12", conn)
{
var result = command.ExecuteScalar();
Console.WriteLine("The total_amount for the account is {0}", result);
}
}
The ExecuteScalar() method on SqlCommand returns the value in the first column of the first row that your query returns, which is ideal in this situation.
If you absolutely have to use a dataset then you'd want to do the following:
using(SqlConnection conn = new SqlConnection(#"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true"))
{
conn.Open()
using (SqlDataAdapter adapter = new SqlDataAdapter("select total_amount from debit_account where account_no=12", conn)
{
var ds = new DataSet();
adapter.Fill(ds);
Console.WriteLine("The total_amount for the account is {0}", ds.Tables[0].Rows[0][0]); // Get the value from the first column of the first row of the first table
}
}
Note: I've wrapped both examples in the C# using statement, this ensures that all your database resources are cleaned up so you don't have any problems with with leaking unmanaged resources. It's not particularly difficult or complicated so is well worth doing
I think, in this case, you'd be better off (performance-wise) to use a SqlCommand instead of the adapter and dataset, and invoke the ExecuteScalar method.
See http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
If you must use the data set, however, ds.Tables[0].Rows[0]["total_amount"] should retrieve your value. You will probably need to type cast the value, though.

Categories