Cast error on GridView Sorting event - asp.net

I'm intercepting the RowDatabound event and using:
DbDataRecord record = (System.Data.Common.DbDataRecord)e.Row.DataItem;
to get access to the unbound data source columns. It works fine on page load and when I apply a filter to the dataset. However, when I attempt to initate a sort on a GridView Column, I get :
Error: Unable to cast object of type 'System.Data.DataRowView' to type 'System.Data.Common.DbDataRecord'
I think I've traced the root issue back to the bind method used in the sort:
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
if (eventArgs != null)
{
DataSet SortedData = new DataSet();
ds.Tables[0].DefaultView.Sort = eventArgs.SortExpression + " " + GetSortDirection(eventArgs.SortExpression);
SortedData.Tables.Add(ds.Tables[0].DefaultView.ToTable());
GridView1.DataSource = SortedData;
}
else
{
GridView1.DataSource = ds;
}
GridView1.DataBind();
}
I remember this was a major pain to figure out because only Dataset had a Sort Property

Since you assign a DataSet to GridView1.DataSource, then the type of e.Row.DataItem in the RowDatabound event will be a DataRowView instead of a System.Data.Common.DbDataRecord. You need to change this:
DbDataRecord record = (System.Data.Common.DbDataRecord)e.Row.DataItem;
to this:
DataRowView record = (DataRowView)e.Row.DataItem;

Instead of trying to sort the Dataset, I appended the sort direction and column from the viewstate to the query before binding it to the grid using SqlDataReader. Looks like I went out of my way to make a simple thing hard to begin with...

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
}

Radtrelist binding

I am trying to bind the simple employee table to Radtreelist but it shoes only columns not data.
source view-->
following is code that i used to bind data to Radtreelist control
void binddata()
{
cn = new
SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
strquery = "select Emp_Id,Emp_Name,Emp_Salary,DeptID from Employee";
da = new SqlDataAdapter(strquery, cn);
dt = new DataTable();
da.Fill(dt);
RadTreeList1.DataSource = dt;
RadTreeList1.DataBind();
}
and table having field Emp_Id,Emp_Name,Emp_Salary,DeptID
so when i run the application it shoes only column of database
You're probably not setting the DataKeyNames and ParentDataKeyNames properties of the RadTreeList
Check the demo here.

How to sync Datagridview and datasource when user sorts column?

I have a DataGridview in a windows form project that is directly bound to a Dataset through a SqlDataAdapter. I have one editable column which a user can edit and that works great if the user does not sort the column.
If the user sorts the column the underlying datasource gets out of sync with what the Datagridview is displaying.
What is a standard technique to keep the gridview and datasource in sync when a user sorts it?
Thanks!
As per my understanding auto sorting does not works with DataGridView, for performing sorting you need to sort the datasource and then rebind it to the GridView as shown in code below
private void Sort_DataGrid(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
// Never use Queries like this always use Stored procedures
SqlCommand myCommand = new SqlCommand("SELECT * FROM Categories", myConnection);
myCommand.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
myAdapter.Fill(ds, "Categories");
DataView dv = new DataView(ds.Tables["Categories"]);
if ((numberDiv % 2) == 0)
dv.Sort = e.SortExpression + " " + "ASC";
else
dv.Sort = e.SortExpression + " " + "DESC";
numberDiv++;
myDataGrid.DataSource = dv;
myDataGrid.DataBind();
}
I can't seem to find an event that triggers for clicking on the header to sort a datagridview.

Get Column Names from SQLDatasource

So I'm using a SQL data source that fires a Store procedure using the selected value of a drop down list as a parameter to return one of a multitude of differing tables. Then I have a gridview that uses this SQLdatasource as it's datasource to display the returned values.
What I want is to be able to get at the column names at run time so that I can use it in a later method. However the SQLDatasource doesn't seem to have a property to get at this data and when I try to get at the columns of the Datagridview after I databind it the gridview only shows a single column (the auto-generated select column). Is there a way to get at this?
I don't know about using the SQLDatasource, but you can do this easily in the codebehind if you load your data into a DataTable. E.g.
var dt = new DataTable();
var connectionString = "your connection string";
using (var db = new SqlConnection(connectionString))
{
var command = new SqlCommand("stored_procedure_name", db);
command.CommandType = CommandType.StoredProcedure;
db.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
}
var columns = dt.Columns;
Each column has a ColumnName property. You can use Linq to get the column names as an array:
var columnNameArray = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();

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

Resources