Data Table loads only last record of mysqlDataReader - asp.net

In my page mysqlDataReader returns 4 records.Whenever I load this mysqlDataReader to DataTable
using
DataTable dt = new DataTable();
dt.Clear();
dt.Load(dr);
DataTable shows only last record.
my Code is:
DataTable dt = new DataTable();
for (int i = 0; i < gvDemoBatches.Rows.Count; i++)
{
CheckBox cb = (CheckBox)gvDemoBatches.Rows[i].FindControl("checkSelect");
if (cb.Checked == true)
{
Panel2.Visible = true;
objBEBatch.BatchID = Convert.ToInt32(((Label)gvDemoBatches.Rows[i].Cells[0].FindControl("lblBatchId")).Text);
MySqlDataReader dr = objBLAddNewDemo.GetParticularDemoData(objBEBatch);
dt.Clear();
dt.Load(dr);
}
}
"GetParticularDemoData" stored Procedure Returns 7 rows.but datatable shows only last record.
Thanks in Advance,
Ratnam.

First please write proper/full code so one can understand !
According to your code, dr is a data row,and dr will contain single row at a time,
It seems you may have taken dr in loop,so at last it will contain last record only.
so your data table displays last record.!

your are adding rows to datatable inside loop. So the last loop record will be saved in the datatable
for (int i = 0; i < gvDemoBatches.Rows.Count; i++)
{
will execute multiple times and inside this you have
MySqlDataReader dr = objBLAddNewDemo.GetParticularDemoData(objBEBatch);
dt.Clear();
dt.Load(dr);
So the data table will contain the data only for the last row of the gridview where cb.Checked == true)

It looks like you are iterating your reading with clearing your table on each iteration. Try to use DataAdapter instead
var adapter = new SqlDataAdapter(query);
adapter.Fill(dt);

Related

How to display a single row in asp.net web forms?

I ask myself how I can display a single row from a datatable object in a control like a gridview.
I already did it with label objects like here: (this is in load event. I already have buttons which increment the zero and decrement)
Tbname.Text = (dset.Tables("coduta").Rows(0).Item("Firma"))
TbStraße.Text = (dset.Tables("coduta").Rows(0).Item("Straße_Firma"))
TbHausnummer.Text = (dset.Tables("coduta").Rows(0).Item("Hausnummer_Firma"))
TbOrt.Text = (dset.Tables("coduta").Rows(0).Item("Ort_Firma"))
the point is I want to show the specific row in something like a gridview control. The only Idea i have is, to create a new table out of the row and that looks like a too complicated way for this. I hope guys can help
cheers steven
I am from C# background but this approach should help you.
Get first row from existing table.
Make clone of existing table.
Add that row to clone table.
Assign that table as datasource for grid
DataRow dr = dset.Tables("coduta").Rows(0);
DataTable dtNew = dset.Tables("coduta").Clone();
dtNew.Rows.Add(dr.ItemArray);
grid.DataSource = dtNew;
grid.DataBind();
try
da = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.SelectCommand = new SqlCommand(#"SELECT * FROM coduta", connString);
da.Fill(ds, "coduta");
dt = ds.Tables["coduta"];
foreach (DataRow dr in dt.Rows)
{
//here is your row of data
}

store datatable into viewstate in asp.net

I've created a DataTable _dt and added columns like below
_dt.Columns.Add("INDATE", typeof(string));
_dt.Columns.Add("INTIME", typeof(string));
_dt.Columns.Add("OUTTIME", typeof(string));
_dt.Columns.Add("OUTDATE", typeof(string));
and I stored _dt into Viewstate:
ViewState["_table"] = _dt;
and then I added a row into that DataTable like this:
DataRow _dr = _dt.NewRow();
_dr[0] = string.Format("{0:dd/MM/yyyy}", System.DateTime.Now);
_dr[3] = string.Format("{0:dd/MM/yyyy}", System.DateTime.Now);
_dt.Rows.Add(_dr);
and bound the DataTable to a gridview successfully.
My problem is: whenever I retrieve the DataTable from Viewstate
DataTable _dtTemp = (DataTable)ViewState["_table"];
the table contains DataRow also...
I don't want the dataRow.. I want table with column field only.
The DataTable object instance stored in the ViewState is the same object instance that you use when adding rows. So, whatever you do with it will be seen when you retrieve it the next time
You could use the Clone method on your original datatable stored in the ViewState and add rows to this clone. In this way you will have two distinct objects and adding rows to the second doesn't affect the first
ViewState["_table"] = _dt;
DataTable temp = _dt.Clone();
DataRow _dr = temp.NewRow();
_dr[0] = string.Format("{0:dd/MM/yyyy}", System.DateTime.Now);
_dr[3] = string.Format("{0:dd/MM/yyyy}", System.DateTime.Now);
temp.Rows.Add(_dr);
....
DataTable temp = (ViewState["_table"] as DataTable).Clone();
....

How to get the sum of a created column from a joined table? SQL / C#

In ASP.NET / C#, I am working with two tables; Cart_LineItems and Products. I have joined the two tables and created a new column called "Extension" that has multiplied the "Products.UnitPrice" times the "Cart_LineItems.Quantity". This is my full SQL query.
SELECT Cart_LineItems.ProductID, Products.Name, Products.UnitPrice,
Cart_LineItems.Quantity, Products.UnitPrice * Cart_LineItems.Quantity
AS Extension, Cart_LineItems.CartNumber
FROM (Cart_LineItems
INNER JOIN Products
ON Cart_LineItems.ProductID = Products.ProductID)
WHERE (Cart_LineItems.CartNumber = ?)
This query is working fine and fills the GridView the way I want it to. How do I get the sum of the fields in the "Extension" column and put the results in a TextBox on a web form?
This is the C# code That I am using in the code behind class.
String strAddSQL = "";
strAddSQL = "SELECT SUM(extension) as subtotal FROM (Cart_LineItems
INNER JOIN Products ON Cart_LineItems.ProductID = Products.ProductID)";
OleDbConnection myAddConn = new OleDbConnection();
OleDbDataReader myAddReader;
myAddConn.ConnectionString = this.SqlDataSource1.ConnectionString;
OleDbCommand myAddCmd = new OleDbCommand(strAddSQL, myAddConn);
myAddConn.Open();
myAddReader = myAddCmd.ExecuteReader();
while (myAddReader.Read())
{
txtSubTotal.Text = Convert.ToString(myAddReader["subtotal"]);
}
myAddReader.Close();
myAddConn.Close();
Thank You
you should try this type:
DataTable dt = new DataTable();
int sum = 0;
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
sum += (int)dr[dc];
}
}

SqlDataSource.Select()? How do I use this? (ASP.net)

I'm trying to retrieve values using VB.NET from a SQL database. How do I use SqlDataSource.Select()? Is there a way to move the value to a variable that I can use for other things?
I know its kind of scattered and vague but that is the best I can do. I basically need to set a labels text to a value in a table.
This puts the result query in to a DataTable.
DataView view = (DataView)dataSource.Select(new DataSourceSelectArguments());
DataTable groupsTable = view.ToTable();
String value;
foreach (DataRow dr in dt.Rows)
{
// Do something here IE grab the value of the first column
value = dr[0];
}
Repying to last question in comment:
YourTable.Rows(index)(index)
YourTable.Rows(index)("columnname")
I was getting crazy trying to do this simple operation:
retrieving data from sqldatasource and put it into variables that I can manipulate.
At the end, Here the working behind code to do this for VB.NET:
Dim DV As New DataView()
Dim DataTable As New DataTable()
Dim SqlDataSource1 As New SqlDataSource()
Dim VALUE As String
SqlDataSource1.ID = "SqlDataSource1"
Me.Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Connection_name").ConnectionString
SqlDataSource1.SelectCommand = "SELECT * from Table"
DV = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
DataTable = DV.ToTable()
For Each riga As DataRow In DataTable.Rows
VALUE = riga("table_name").ToString
Next
the for each, in this case gets only the first value but you can get any value from datatable and put it into vector, or other strings, so you can control data coming from sqldatasource.
ENJOY

how to extract Datatable or DataSet from Linq Query or List

how to extract DataTable or DataSet from Linq Query or List.
e.g I have linq query like this
MyDBpDataContext dcSp = new MyDBpDataContext();
dcSp.myProgrammSP().ToList();
I wrote an Sp which sends a Table as result and I have code which is already using DataTable So I want to convert this result in DataTable.
The result doesn't exist as a DataTable at any point, so if you want it as a DataTable, you have to create one and copy the data into it.
Example:
DataTable table = new DataTable("Items");
table.Columns.Add(new DataColumn("Id", typeof(Int32)));
table.Columns.Add(new DataColumn("Name", typeof(String)));
foreach (Item item in items) {
DataRow row = table.NewRow();
row["Id"] = item.Id;
row["Name"] = item.Name;
table.Rows.Add(row);
}

Resources