sql 2005 xml passed to asp.net grid with date formating - asp.net

i have sql that uses FOR XM RAW to generate xml for my asp.net application to use to bind grids to and things like this.
the problem is that the date data is not taking the gridView formatting of the date because (and im taking a crack at this) the date value in the xml is a string and the formatting is not taking.
any thoughts on how to get this to work?
i like using xml because i can persists it to a log table and trace all the xml sent in and out. i would hate to loose this...

You can use code on the RowDataBound event to reformat programatically. Here is a try in VB.
Private Sub gvXML_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvXML.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
if IsDate(e.Row.Cells(1).Text) then
e.Row.Cells(1).Text = CDate(e.Row.Cells(1).Text).Format("LongDate")
End If
End If
End Sub
P.S. this is quickly modified from something else I am doing. It is not tested.

Related

Making combobox_selectedIndexChanged work

I have a web page that on page load loads data into drop down lists and the user has the option to change the values if they wish too. How do I make it so everytime they change the value it will save it and resend it to the database? So far all I have is this:
Private Sub cboCure_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboCure.SelectedIndexChanged
cboCure.SelectedItem.Text = CStr(sender)
...database functions using cboCure.SelectedItem.Text
End Sub
I don't know if this is enough information to help out at all, if it's not just lemme know... I don't really know what else to put in this one.
Set autopostback property of your combobox to true. So that, whenever a change happens; you can check if if(ispostback) and have your code to do the insertion of changed data in DB.

SqlDataSource reuse on different pages

I am using ASP.NET. I have a ReportPage1 and ReportOutputPage1. These are different aspx files and has different MasterPages. However, I need the same SqlDataSource object to use on both pages. On ReportPage I need SqlDataSource to call StoredProcedure and import data to CSV file, but on ReportOutputPage I need to use SqlDataSource to call the same StoredProcedure and populate GridView.
ReportPage1 is "main" page - a button click from this page opens ReportOutputPage1 and displays it in new window. ReportPage is PreviousPage for ReportOutputPage1.
Above is example for Report1. The same idea is for Report2 (with SqlDataSource2) and for Report3 (SqlDataSource3) etc. - 10 different reports.
How to reuse SqlDataSource for every two pages (ReportPage & ReportOutputPage)?
First suggestion I found in web - using masterpage for both ReportPage and ReportOutputPage. This doesn't work, as I have already have different masterpages for ReportPage and ReportOutputPage, as well as then I need to create 10 different MasterPages for each Report.
Second suggestion was to define SqlDataSource on ReportPage and then reuse it using PrevousePage on ReportOutputPage, but this doesn't work for my special case (I am using Ajax staff and Partial page postbacks and I am loosing PreviousPage, also SqlDataSource could not be serialized to save it in ViewState or similar).
Create UserControl. Probably this could work, but it is time consuming to create UserControl every time for new Report (10 reports - 10 usercontrols?).
Simply Copy & Paste SqlDataSource (I did it for one Report) could work, but I would like something more like code reuse. Someone could simply forget to modify SqlDataSource in two different places if necessary.
Can you, please, give me some suggestions how to reuse code (particularly, SqlDataSource) for Report & ReportOutput pages?
Could you define the need for using the same SqlDataSource? If they are two different pages and it sounds like two different uses why not use two different SqlDataSource? The pages are separate anyhow, your not going to be able to share an object on one with the other.
I would suggest you look at adding a data layer to your application for database interaction and binding your data to the datagrid at request time. That way you build your database interaction once and reuse that over different pages.
The other option is you simply use two SqlDataSources and copy/paste them to both the pages. If your trying to make a selection or some sort of criteria apply to your second page then consider using query strings and QueryStringParameters in your SqlDataSource.
Hope this helps.
Edit: Pop this in App_Code somewhere, pass in your specific usage requirements.
Public Shared Function GetData(connString As String, command As String, Optional params As SqlParameter() = Nothing) As DataTable
Dim conn As New SqlConnection(connString)
Dim da As New SqlDataAdapter(command, conn)
Dim dt As New DataTable
da.SelectCommand.CommandType = CommandType.StoredProcedure
da.SelectCommand.CommandTimeout = 6000 '6 seconds.
If Not IsNothing(params) Then
For Each p As SqlParameter In params
da.SelectCommand.Parameters.Add(p)
Next
End If
Try
conn.Open()
da.Fill(dt)
Return dt
Catch ex As Exception
Throw ex
Finally
conn.Close()
End Try
End Function
Then bind the datatable to your gridview, not sure how your outputing to file.
Private Sub BindData(gridview As GridView, data As DataTable)
gridview.DataSource = data
End Sub
You can now re-use the database interaction from the code behind:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
BindData(MyGridView,GetData(ConnectionStrings(connName).ConnectionString, _
"dbo.SomeSprocOrOther", _
New SqlParameter(){New SqlParameter("paramName","paramValue")})
End Sub

DevExpress AspxGridView GetRowValues during BeforePerformDataSelect Event

So, I have a master grid and a detail grid within that master grid.
I am grabbing the masterkey from my parent grid via the BeforePerformDataSelect and placing this value into a session variable. At that point I also need to grab a value from the specific row that I am on. Lets call that variable SENT_DATE.
Here is some sample code.
Protected Sub gvDetails_BeforePerformDataSelect(ByVal sender As Object, ByVal e As EventArgs)
Dim gvDetails As ASPxGridView = (TryCast(sender, ASPxGridView))
Session("ID_NUMBER") = gvDetails.GetMasterRowKeyValue
Session("SENT_DATE") = gvDetails.GetRowValues("SENT_DATE")
End Sub
I have worked with DevExpress products a lot before but it has been quite some time. If I remember correctly, normally I just grab the e.VisibleIndex and I am able to go from there but in this specific event I am unable to grab this. I know the above code is incorrect for grabbing the variable SENT_DATE, but I am not sure what to do here.
Any ideas, advice would be greatly appreciated. Thanks. I have searched the DevExpress forums deeply.
You can use FocusedRowIndex property.
Session("SENT_DATE") = gvDetails.GetRowValues(gvDetails.FocusedRowIndex, "SENT_DATE")

How to register data for validation using RegisterForEventValidation in asp.net

I would like to know the method of using RegisterForEventValidation in asp.net
My problem is this.
If I enable eventvalidation, then changing the controls using javascript and then posting the information back to the server later on throws up an error.
But If I disable event validation, the data present/selected in the controls is not available in the event handlers in code behind.
So, how should one resolve such issues?
Also, are there are any good articles that explain the issue and a resolution in detail? Tried googling. Came across many articles. But nothing that matched my expectations.
A small progress.
If I do the below, the event validation error goes away, but am not able to get the selected value in the code behind on button click (after selecting "1" in the dropdown, since for now I have registered only that value)
I get a runtime error - Unable to convert from string to double when I try accessing the selected value in drop down in code behind (The reason I believe is that no value is passed in the first place).
Any idea on what might be going wrong here!? Thanks!
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
Page.ClientScript.RegisterForEventValidation(Me.ddldobddId.UniqueID, "1")
MyBase.Render(writer)
End Sub
Protected Sub btnId_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnId.Click
If CType(Me.ddldobddId.SelectedValue, Integer) = 0 -> Throws the error
End Sub
You've pretty much got it. The DropDownList.SelectedValue is always going to be a System.String type.
You must convert the String to an Integer in your btnId_Click method.
Protected Sub btnId_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnId.Click
Dim convertedSelectedValue As Integer
convertedSelectedValue = Convert.ToInt32( Me.ddldobddId.SelectedValue )
End Sub

Why is the DataBind() method necessary?

Simple question, I guess.
For a long time I've blindly followed a (supposedly) common pattern when programmatically databinding my ASP.NET controls. Namely:
gridView1.DataSource = someList;
gridView1.DataBind();
However, if I were setting my GridView to bind to a DataSource control via the DataSourceID property, the call to DataBind() is unnecessary. Namely:
gridView1.DataSourceID = LinqDataSource1;
is sufficient.
Furthermore, if you try to set the DataSource property in ASPX markup, you are greeted with the following:
You cannot set the DataSource property declaratively.
I assume these are related, but I am still stumped as to why DataBind() is necessary. The difference between DataSource and DataSourceID is secondary - I can understand some magic taking place there. The real question is why doesn't the DataSource propery setter cause databinding automatically? Are there any scenarios in which we want to set the DataSource but not bind to it?
In ASP.Net, it's often important to have certain data available and ready at certain points in the page life cycle, and not before. For example, you may need to bind to a drop down list early to allow setting the selected index on that list later. Or you might want to wait a bit to bind that large grid to reduce the amount of time you hold that connection active/keep the data in memory.
Having you explicitly call the .DataBind() method makes it possible to support scenarios at both ends of the spectrum.
DataSource is a property of the BaseDataBoundControl class. DataSourceID is a property of the DataBoundControl class, which inherits from BaseDataBoundControl and did not exist before ASP.NET 2.0.
Since DataBoundControl is explicitly for displaying data in a list or tabular form, and BaseDataBoundControl cannot make that assumption, binding is not automatic when DataSource is set because the type of control may not match the structure of the data.
Of course, this is all just a guess based on the MSDN documentation, so I could be wrong.
I noticed that without using DataBind() that nothing will be displayed in my GridView so I always include it as shown in this section of code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' TableAdapter object.
' Provide communication between this application and the database.
'-----------------------------------------------------------------
Dim suppliersAdapter As New SuppliersTableAdapter
' Get the data from the TableAdapter into the GridView.
'------------------------------------------------------
GridView1.DataSource = suppliersAdapter.GetSuppliers()
' Display the result set from the TableAdapter in the GridView.
'--------------------------------------------------------------
GridView1.DataBind()
End Sub
Please forgive the extra commenting as I'm also still learning ASP.Net as well and the comments will help me learn better "what and why" to use certain statements.
Try this:
if (GridView1.EditIndex == e.Row.RowIndex)
{
TextBox t2 = (TextBox)e.Row.FindControl("TextBox2");
DateTime dt2;
if (DateTime.TryParse(t2.Text, out dt2))
{
t2.Text = dt2.ToString("yyyy-MM-dd");
}
}

Resources