Store DataSet when ending looping in C# - c#

I am using this code to fill DataSet
var ds = new DataSet();
List<string> list = new List<string>();
foreach (DataGridViewRow row in grdInterPOList.Rows)
{
DataGridViewCheckBoxCell chk = row.Cells[0] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(chk.Value) == true)
if (row.Cells.Count >= 2 && row.Cells[1].Value != null)
{
list.Add(row.Cells[1].Value.ToString());
}
}
foreach (var _PO_No in list)
{
ds= ShippingData_Export(_PO_No);
}
private DataSet ShippingData_Export(string X_PO_NO)
{
var ds = new DataSet();
var sqlConn = new SqlConnection(strConStr);
try
{
sqlConn.Open();
var cmd = new SqlCommand("proc_TBL_PO_M_ShippingExcel", sqlConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#X_PO_NO", X_PO_NO);
var da = new SqlDataAdapter(cmd);
da.Fill(ds);
sqlConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return ds;
}
If we select more than 1 _PO_No , then we only get the last value after looping.
So my question is how to store DataSet value after end loop.
For example: If we select 2 _PO_No : GV01 and GV02 then after ending loop . We will get both 2 _PO_No not only the last one (GV02)

The problem in your code is:
foreach (var _PO_No in list)
{
ds = ShippingData_Export(_PO_No);
}
You are looping through your list and calling ShippingData_Export on each item in the list but you're then overwriting ds each time you call this method. This is why only the last value is stored.
If you want to have a single DataSet contain multiple results, you need to pass your DataSet to the ShippingData_Export method and add your results to it instead of creating a new one each time.
The result would be something like this:
foreach (var _PO_No in list)
{
ShippingData_Export(_PO_No, ds);
}
private void ShippingData_Export(string X_PO_NO, DataSet ds)
{
var sqlConn = new SqlConnection(strConStr);
try
{
sqlConn.Open();
var cmd = new SqlCommand("proc_TBL_PO_M_ShippingExcel", sqlConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#X_PO_NO", X_PO_NO);
var da = new SqlDataAdapter(cmd);
da.Fill(ds);
sqlConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return ds;
}
A couple of other small issues with your code:
Add { } to the block after the line if (Convert.ToBoolean(chk.Value) == true). Get used to using { } explicitly to make your code more readable.
You are manually opening your SQL Connection but you don't close it when an exception happens. Look into the using statement to make sure you always close your connection even when things go wrong.

Related

display data to listbox C#

Listbox does not show data. Verified data is in database and I am not getting an
error. Not sure where/what is wrong. Thanks in advance. My code is attached.
private void UpDateList()
{
// add data connection and fill data set.
SqlConnection conn = new SqlConnection(dataSource);
DataTable dt = new DataTable();
string sqlString = "select * from Suppliers";
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = sqlString;
da.Fill(ds);
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
foreach(DataRow dRow in ds.Tables[0].Rows)
{
ArrayList values = new ArrayList();
foreach(object value in dRow.ItemArray)
{
values.Add(value);
_Suppliers.Add(values);
}
}
lstSuppliers.DataSource = _Suppliers;
lstSuppliers.Update();
}
It's kinda pointless to enumerate one bindable data collection and transfer data into another bindable collection so it can be bound. Just have your list use the default view of the datatable that already holds the data (allows sorting, filtering etc)
E.g.
LstSuppliers.DataSource = ds.Tables[0].DefaultView;
LstSuppliers.DisplayMember = "column name goes here of what to show eg SupplierName";
LstSuppliers.ValueMember = "column whose value to use for lstSuppliers.SelectedValue e.g. supplierId";
And then for example, not required but an example possibility:
ds.Tables[0].DefaultView.Sort = "[SupplierName] ASC";

adapter.Fill takes long time to run

I have an ADO.NET code to make a server call with input parameters and return Dataset. I am using SqlDataAdapter to get data and assign it Dataset.
Here is my code
public DataSet GetRecordsWithParam(string spName, Dictionary<string, dynamic> ParaArr)
{
try
{
Connection();
DataSet ds = new DataSet();
cmd = new SqlCommand(spName, con);
cmd.CommandTimeout = 300;
cmd.CommandType = CommandType.StoredProcedure;
if ((ParaArr != null))
{
foreach (KeyValuePair<string, dynamic> kvp in ParaArr)
{
cmd.Parameters.Add(kvp.Key, kvp.Value);
}
}
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlDataAdapter myAdapter = new SqlDataAdapter(cmd);
myAdapter.Fill(ds);
return ds;
}
catch
{
throw;
}
finally
{
con.Close();
}
}
But it takes too much time to execute the line
myAdapter.Fill(ds);
There is no problem with my procedure. While assigning the data from myAdapter to ds using Fill it takes too much time. It is a global method I am using in my project, most of the time it works fine. But only when called from this method
private DataSet PayPeriodFromCountryCompany(string Country, string Company, string EmployeeType, string startDate, string EndDate, string Action)
{
Dictionary<string, object> Dic = new Dictionary<string, object>();
DBConnection DB = new DBConnection();
DataSet _dsPayPeriod = new DataSet();
string _strConnectionString = ConfigurationManager.ConnectionStrings["TimesheetconnString"].ConnectionString;
try
{
Dic.Add("#Country", Country);
Dic.Add("#Company", Company);
Dic.Add("#EmployeeType", EmployeeType);
Dic.Add("#StartDate", startDate);
Dic.Add("#EndDate", EndDate);
Dic.Add("#Action", Action);
_dsPayPeriod = DB.GetRecordsWithParam("TSTime_spTimesheetToCPS", Dic);
return _dsPayPeriod;
}
catch
{
throw;
}
}
loading problem. It takes 1-2 minute to execute the line ' myAdapter.Fill(ds); '.
Anyone point if there is any bug in the code. Thanks in Advance

Getting value from last row of SQL Server database C#

public queue getQueueDataByID(int queueID)
{
string DBConnect = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlDataAdapter da;
DataSet ds = new DataSet();
queue myQueue = new queue();
StringBuilder sqlCommand = new StringBuilder();
sqlCommand.AppendLine("Select * from QueueTable where");
sqlCommand.AppendLine("id = #paraId");
try
{
SqlConnection myConn = new SqlConnection(DBConnect);
// sqlCommand.Parameters.AddWithValue("paraCustId", tbCustId.Text);
da = new SqlDataAdapter(sqlCommand.ToString(), myConn);
da.SelectCommand.Parameters.AddWithValue("paraId", queueID);
// fill dataset
da.Fill(ds, "QueueTable");
//conn.Close();
int rec_cnt = ds.Tables["QueueTable"].Rows.Count;
DataRow row = ds.Tables["QueueTable"].Rows[rec_cnt-1 ];
myQueue.queueNo = row["QueueNo"].ToString();
myQueue.NRIC = row["NRIC"].ToString();
myQueue.ContactNo = row["ContactNo"].ToString();
}
catch (SqlException ex)
{
}
return myQueue;
}
This is my class,I am trying to retrieve the datas from the last row of the database to display in a web form, any idea how i can do that? My "id", primary key is set as autoincrement.
You can use Linq on the datatable to get the last row.
var queueDataTable = ds.Tables[0];
var lastDataRow = queueDataTable.AsEnumerable().Last();
If you need to itterate through all the rows in the datatable
foreach (var dataRow in queueDataTable.AsEnumerable())
{
}
thanks

How to add an extra Item in ComboBox using c#

Currently i'm populating a combobox with items from a database.However, i want the first item of combobox to be "---Select---".I am using the following code.All the items from database are getting populated but not the item "---Select---". Any help in this regard is highly appreciated.
private void popClass()
{
cmbClass.Items.Clear();
DataSet ds = new DataSet();
cmbClass.Items.Add("---Select----");
string sqlPS = #"SELECT * FROM tblclass_msb";
try
{
using (FbConnection conPS = new FbConnection(connectionString))
{
conPS.Open();
using (FbCommand cmdPS = new FbCommand(sqlPS, conPS))
{
using (FbDataAdapter da = new FbDataAdapter())
{
da.SelectCommand = cmdPS;
da.Fill(ds);
cmbClass.DataSource = ds.Tables[0];
cmbClass.ValueMember = "c_id";
cmbClass.DisplayMember = "c_name";
}
}
}
}
catch (FbException ex)
{
MessageBox.Show("PC-->>" + ex.Message);
}
}
i have tried other solutions mentioned somewhere in the other threads but its not working for me
you have to add new row at zero position you an do it like this:
private void popClass()
{
cmbClass.Items.Clear();
DataSet ds = new DataSet();
cmbClass.Items.Add("---Select----");
string sqlPS = #"SELECT * FROM tblclass_msb";
try
{
using (FbConnection conPS = new FbConnection(connectionString))
{
conPS.Open();
using (FbCommand cmdPS = new FbCommand(sqlPS, conPS))
{
using (FbDataAdapter da = new FbDataAdapter())
{
da.SelectCommand = cmdPS;
da.Fill(ds);
DataRow dr=ds.Tables[0].NewRow();
dr["c_id"]=0;
dr["c_name"]="--Select--";
ds.Tables[0].Rows.InsertAt( dr,0);
cmbClass.DataSource = ds.Tables[0];
cmbClass.ValueMember = "c_id";
cmbClass.DisplayMember = "c_name";
}
}
}
}
catch (FbException ex)
{
MessageBox.Show("PC-->>" + ex.Message);
}
}
If you were connecting to SQL Server using SqlCommand, you could simply change the SQL statement to the following:
string sqlPS = #"select 0 as c_id, '--Select--' as c_name union SELECT c_id, c_name FROM tblclass_msb";
However, it looks like you're connecting to Firebird and I can't be sure if union is supported.

How to Stop DataGrid on Adding Rows?

This is my Method:
Datatable data2 = new Datatable();
int result = 0;
using (SqlConnection conn = new SqlConnection(connStr))
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "SELECT * from TableA";
SqlDataAdapter da = new SqlDataAdapter(cmd);
result = da.Fill(data2);
if (result > 0)
{
this.dgBatch.DataSource = data2;
}
else
{
MessageBox.Show("No Records!");
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
If I call this Method consecutively it always Add Rows from the first Query.
Ex:
Table Data: 5
First Call: 5
Second Call: 10. It duplicates all Records from first Call.
Thanks in Regards
That is because you are reusing data2. You should create a new instance for data2 before the following line:
result = da.Fill(data2);
Assuming data2 is a datatable
result = da.Fill(data2); will always merge the results because you are using same instance of datatable.
if you want to get every time a fresh copy than create a new instance of datatable and than fill this instance with data.
so the line before result = da.Fill(data2); add following line.
data2 = new Datatable();

Categories