DataTable's Default View is different from Actual Table Data - asp.net

I'm using a huge datatable for a survey analysis. Instead of calling SQL server frequently am using row filtering on this datatable using DataView.
But the problem is once I filter the DataTable by
dv= dt.defaultview
dv.rowfilter="id=10"
that works fine. Dv having a filtered rows
But when we assign the same dt to another view, the Main datatables Default view being changed based on the filteration done for DV which is ID=10
So in the immediate window I checked this
dt.defaultview.totable().rows.count
and its 20 (WHich was because of the filteration done for DV)
but
dt.rows.count
is 1500 which is the correct count.
But my question is how this happened since I didnt touched the Datatable and I assigned the filter for DV only. Even then how the defaultview of the datatable changed?

"Even then how the defaultview of the datatable changed?" Isn't that obvious if you look at the first two lines of code you have posted?
dv = dt.DefaultView
dv.rowfilter = "id=10"
If you want to remove that filter on the DefaultView you have to assign empty string or Nothing:
dt.DefaultView.RowFilter = ""

Related

Can't set ASP.NET drop down list to return query value in a datatable

Ok so I have been searching for three days and so far I can not find an answer that explains what I need to do.
Here is what I need. I have an asp.net content page. On that page there are some drop down list boxes. I have a query that fetches data from a SQL DB and puts in a Data table and that is working fine.
What I am trying to do is set the text of the ddl to a string that has been returned from the query.
Here is the HTML side:
<asp:DropDownList ID="ddlProbType" CssClass="ddlEdit" runat="server" Width="150px" DataSourceID="SdsProbType" DataTextField="probtype" DataValueField="probtype" />
Here is the VB code behind:
If dt.Rows.Count > 1 Then
stupidString = dt.Rows(RowCount)("probtype")
ddlProbType.SelectedValue = stupidString
Else
stupidString = dt.Rows(RowCount)("probtype")
ddlProbType.SelectedValue = stupidString
End If
I have added the variable stupidString and the set a break point to check the value being returned and it is correct. When the next line executes the ddl does NOT get the text assigned. I can mouse over the variable stupidString and see that the value it was assigned from the query is correct.
When I have tried setting the ddl directly from the data table, I have tried .ToSting() and .ToString.Trim() to the end of the dt.Rows line but it just will not assign!!
I know this probably something really stupid that I am not doing or overlooking but can anyone help? I do not want to assign a whole sql table to the ddl I just want to set the current list to the value that is returned by the sql query.
You need to populate the list first, e.g. by using
ddlProbType.Items.Add(New ListItem("Key","Value"))
or by using Data Binding.
After the list is populated, then you can tell the control which item should be selected.

how to update specific table inside dataset in asp.net

i have a dataset which contains three tables dt1, dt2, and dt3 (in the sequence), now i am maintaining the viewstate for every table, to retain the table across postback, (i.e i have latest DataTable inside viewstate), now the problem is i want to apply ViewState of dt3 to the respective table in DataSet, i.e dt3, i am doing below:
dataSet.Tables[(it will be dynamically fetched, say for here its) 0] = ViewState["DataTable" + (it will be dynamically fetched, say for here its) 0]
but here i am getting error saying dataSet.Tables[] is read-only.
can any one help how shall i go about at. Let me know if anyone needs more information about my question.
You should use
DataSet ds = new DataSet();
ds.Tables.Add(YourDataTable);
OR
ds.Tables.AddRange(YourDataTableArray);
To update an existing table in ds from ViewState you can try two approaches.
Remove Table from DataSet by using DataSet.Tables.Remove("Table"); method, Note that you should not rely on index approach to fetch Tables from DataSet instead you should provide your Tables a unique name so that you can fetch and remove them when you want to.
You can use loop approach to fetch rows from your ViewState DataTable and then insert them into DataSet's Table one by one, Something like this.
ds.Tables[0].Rows.Clear();
DataTable dtFromViewState = ViewState["dt"] as DataTable;
foreach (DataRow row in dtFromViewState.Rows)
ds.Tables[0].Rows.Add(row.ItemArray);

Loading data into labels with DataReader where unsure of total rows in query result

How would you write the code to read the data from a query and display each row in a separate label if you don't know how many rows the query result may contain? If you try to read one too many rows with the DataReader, it throws an excetion when you try to read the column data on the row that doesn't exist. I'm not sure how to code this.
If dr.HasRows Then
dr.Read()
LN2.Text = dr.Item("linenum").ToString
Else
LN2.visible = False
End If
This example shows how I am loading the second row with the DataReader. This works if there are two rows of data, but if there is only one row of data, it throws an exception. I have a maximum of 12 rows of data but, but my actual query results may contain anywhere between 1 and 12 rows of data.
The Read method returns a boolean indicating whether or not the read of the next row was successful. Therefore, you could change your code to something like this:
If dr.Read() Then
LN2.Text = dr.Item("linenum").ToString
Else
LN2.visible = False
End If
However, usually, in such cases, displaying varying numbers of rows of data in a fixed number of labels isn't the best approach. For instance, if you used a single ListBox control instead, all your loading code could be simplified to the following:
While dr.Read()
ListBox1.Items.Add(dr.Item("linenum").ToString())
End While
If you need to show multiple columns of data for each row, I would recommend using either a ListView control (with the View property set to Details) or a DataGridView control.

Using SELECT DISTINCT on an already created DataTable object?

I have an already created DataTable object which i am using for my girdview (asp.net) i also need to bind a column of that object to a DropDownList. The datatable has the correct details in the column but the column contains more that 1 of the same name in the column - hence I would love to just do some kind of SELECT DISTINCT on the datatable and copy it to a new datatable for use with binding the dropdown.
This would allow me to save resources by making another trip to the database.
Here is an example, the current datatable has a column called items and in this column has the following entries
1
1
1
1
5
5
6
And of course i need only unique items for binding to my dropdown, hence i need the following data
1
5
6
Of course i don't want to change the original datatable object but rather make a copy of it will the new details
Any ideas if this is possible ? Or do i need to make another trip to the db?
thanks in advance
DataTable dt = new DataTable();
dt = dsMobileInfo.Tables[0].DefaultView.ToTable(true, "ColumnName");
//Applying the dvResult data set to the Grid
for(int i=0;i
Hope This will work for you.
You should use ToTable() on your default view (or any other view you are using) and provide true, to indicate you want distinct records:
DataTable distinctTable = originalTable.DefaultView.ToTable(true);

Sort a GridView Column related to other Table

i have a GridView bound to a DataView.
Some columns in the DataView's table are foreignkeys to related tables(f.e. Customer). I want to enable sorting for these columns too, but all i can do is sorting the foreignkey(fiCustomer) and not the CustomerName.
I have tried this without success(" Cannot find column ERP_Customer.CustomerName "):
<asp:TemplateField HeaderText="Customer" SortExpression="ERP_Customer.CustomerName" >
A tried also the DataViewManager, but i've a problem to detect the table to sort:
Dim daCharge As New ERPModel.dsERPTableAdapters.ERP_ChargeTableAdapter
daCharge.Fill(dsERP.ERP_Charge)
Dim viewManager As New DataViewManager(Me.dsERP)
viewManager.DataViewSettings(dsERP.ERP_Charge).RowFilter = filter
viewManager.DataViewSettings(dsERP.ERP_Charge).Sort = sort 'sort is the GridView's SortExpression
Me.GrdCharge.DataSource = viewManager.CreateDataView(dsERP.ERP_Charge)
I have to apply the sort on a distinct table of the DataViewManager, but this table would differ on the related tables.
I have bound the TemplateColumns in Codebehind in RowDataBound-Event f.e.:
Dim LblCustomer As Label = DirectCast(e.Row.FindControl("LblCustomer"), Label)
LblCustomer.Text = drCharge.ERP_CustomerRow.CustomerName 'drCharge inherits DataRow
What is the recommended way to sort a GridView on columns related to other tables? I could build a custom datatable with the customername instead of the foreignkey and bind this column to the TemplateField. But then my huge dataset in the model makes no sense anymore.
EDIT:
It seems that my question was not clear or too special.
Perhaps i can rephrase it in a more general term.
I have a model with a Dataset. I'm binding one Datatable(ERP_Charge) from it to my GridView(actually i take a Dataview from that Table). In this Datatable are columns that are related to other Datatables in the Dataset(relations are defined). When i want to make the grid sortable its no problem on the columns that belong to ERP_Charge. But the columns with foreign keys to other table could not be sorted because the Gridview shows f.e. not the CustomerID but the Customername. I get the Customername in RowDataBound.
Normally i would join the tables and add a Datacolumn for the Customername. Then i set this "virtual" Datatable as Datasource from the Gridview and i'm able to sort it. But i didnt want to create the datatables in the Page on the fly(it belongs into the model). Do i have to define it in the dataset-Designer? I thought it would be sufficient to define the relationships in the dataset.
UPDATE: i had solved my sorting problems as below.
Regards
UPDATE: i had solved my sorting problems in the following way: I changed my DataSet in the model and joined the related table to the Main-Table(ERP_Charge). I added the columns to the Datatable(f.e. CustomerName) that i want to sort. But i did that without saving it in the configuration wizard of the DataAdapter, because that would delete all Update-,Delete- and InsertCommands. Hence i changed only the SelectCommand with the one that was generated from the Wizard. Therefore i kept the benefit of my Datamodel with the ability to sort for columns of related tables. Maybe queries are a little slower now because of the joins but it works for me.

Resources