ASP.NET OleDbConnection Problem - asp.net

I'm working on an ASP.NET website where I am using an asp:repeater with paging done through a VB.NET code-behind file. I'm having trouble with the database connection though. As far as I can tell, the paging is working, but I can't get the data to be certain.
The database is a Microsoft Access database. The function that should be accessing the database is:
Dim pagedData As New PagedDataSource
Sub Page_Load(ByVal obj As Object, ByVal e As EventArgs)
doPaging()
End Sub
Function getTheData() As DataTable
Dim DS As New DataSet()
Dim strConnect As New OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;Data Source=App_Data/ArtDatabase.mdb")
Dim objOleDBAdapter As New OleDbDataAdapter("SELECT ArtID, FileLocation, Title, UserName, ArtDate FROM Art ORDER BY Art.ArtDate DESC", strConnect)
objOleDBAdapter.Fill(DS, "Art")
Return DS.Tables("Art").Copy
End Function
Sub doPaging()
pagedData.DataSource = getTheData().DefaultView
pagedData.AllowPaging = True
pagedData.PageSize = 2
Try
pagedData.CurrentPageIndex = Int32.Parse(Request.QueryString("Page")).ToString()
Catch ex As Exception
pagedData.CurrentPageIndex = 0
End Try
btnPrev.Visible = (Not pagedData.IsFirstPage)
btnNext.Visible = (Not pagedData.IsLastPage)
pageNumber.Text = (pagedData.CurrentPageIndex + 1) & " of " & pagedData.PageCount
ArtRepeater.DataSource = pagedData
ArtRepeater.DataBind()
End Sub
The ASP.NET is:
<asp:Repeater ID="ArtRepeater" runat="server">
<HeaderTemplate>
<h2>Items in Selected Category:</h2>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" ID="HyperLink"
NavigateUrl='<%# Eval("ArtID", "ArtPiece.aspx?ArtID={0}") %>'>
<img src="<%# Eval("FileLocation") %>"
alt="<%# DataBinder.Eval(Container.DataItem, "Title") %>t"/> <br />
<%# DataBinder.Eval(Container.DataItem, "Title") %>
</asp:HyperLink>
</li>
</ItemTemplate>
</asp:Repeater>

If you need help with Connection Strings, this site is the ultimate resource!
http://www.connectionstrings.com/

Are you creating the connection string by hand? If so...don't do that! Use the Server Explorer to create your connection. Then highlight it and go to the Properties window, and you'll see the connection string it uses.
Also, using the Server Explorer will let you browse through your tables and even open them up to see your data. At least that'll tell you for certain whether your data is accessible.

Problem solved! Pretty much banging my head against the wall now considering how simple it was. It was the Page_Load, I changed it to the following:
Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
doPaging()
End Sub
And voila, it works!
Also, for the connection string, I ended up using:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\ArtDatabase.mdb
Which works great.
Thanks for your help and input guys!

Related

Asp .net Web Forms TreeView - PopulateNodesFromClient

I have control configured as below. control is populated from server without postback to server but after I make postback i can't get checked items. Is there any solution for this or maby there is other idea.
Main issue is to populate treeview without full page postback.
Thx for any help.
<asp:TreeView ShowLines="True" runat="server" ID="trvCategories" ShowCheckBoxes="All" EnableClientScript="True" PopulateNodesFromClient="True" OnTreeNodePopulate="PopulateNode">
</asp:TreeView>
I did something like this in my VB.NET application; it may very well work in ASP.NET also.
Private Sub tvwDataCategory_AfterCheck(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.TreeViewEventArgs) Handles tvwDataCategory.AfterCheck
Dim Node As System.Windows.Forms.TreeNode = eventArgs.Node
Dim n As Integer
If VB.Left(Node.Name, cTagLength) = cDataTypeTag Then
Node.ForeColor = DefaultForeColor
Dim nNodes As TreeNodeCollection = eventArgs.Node.Nodes
For Each nNode As TreeNode In nNodes
If nNodes.Count = 0 Then
If nNode.Checked Then
tvwDataCategory.Nodes.Item(n).Checked = True
Else
tvwDataCategory.Nodes.Item(n).Checked = False
End If
End If
Next
Else
Call FormatChecks()
End If
End Sub
Is this what you're looking for?

How to delete a record using LinkButton and refresh the table?

I have an HTML table to display a set of records from database after user entered a patient code or during Page Load when the patient code is passed through Querystring. Each data row has a Delete link button which is created dynamically.
I'd like to have the table refreshed after deletion. However, whenever the link button is clicked, it will postback and all the records will be wiped out unless I reload the data. If I reload the data again after deletion, there will be 2 times data fetching and the table rows will be doubled.
The first 2 rows of the tables are defined on the ASPX for easier styling purpose. If I cleared the table when fetching the data, the first rows will be wiped out as well. I have another 8 tables on different pages created in the same manner, hence I'd rather find other solution rather than defining and styling the rows from code behind.
Any help will be greatly appreciated.
The codes I use are as follow:
ASPX
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblPatientCode" runat="server" Text="Patient Code : "></asp:Label>
<asp:TextBox ID="txtPatientCode" runat="server"></asp:TextBox>
<asp:Button ID="btnFind" runat="server" name="Date" Text="Find" Width="90" CssClass="ButtonNormal" />
<br /><br />
<table id="tblDoctorInformation" class="PatientDetailsTable" runat="server">
<tr><td colspan="2">DOCTOR INFORMATION</td></tr>
<tr>
<td>Doctor In Charge</td>
<td> </td>
</tr>
</table>
</div>
</form>
</body>
Code Behind:
Protected PM As New PatientManagement.Common
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
GetPatient()
Else
If txtPatientCode.Text <> "" Then
GetPatient()
End If
End If
End Sub
Private Sub GetPatient()
Dim sPatientCode As String = ""
If IsPostBack Then
sPatientCode = Trim(txtPatientCode.Text)
Else
sPatientCode = Trim(Page.Request.QueryString("PatientCode"))
End If
If sPatientCode <> "" Then
Dim dr As SqlDataReader
dr = PM.ExecuteReader("SELECT LOGID,DOCTORNAME FROM PMV_DOCTORINCHARGE WHERE PATIENTCODE='" & sPatientCode & "'")
If dr.HasRows Then
Do While dr.Read
Dim tRow As New HtmlTableRow
Dim tCellDoctorName As New HtmlTableCell
Dim tCellModifyLink As New HtmlTableCell
Dim lb As New LinkButton
'Doctor Name
tCellDoctorName.InnerHtml = PM.GetString_TableCell(dr("DoctorName"))
tRow.Cells.Add(tCellDoctorName)
'Delete links
lb.Text = "Delete"
lb.Attributes.Add("AutoPostBack", False)
lb.CommandArgument = dr("LogID").ToString()
AddHandler lb.Click, AddressOf DeleteRecord
tCellModifyLink.Controls.Add(lb)
tCellModifyLink.Align = "Center"
tRow.Cells.Add(tCellModifyLink)
tblDoctorInformation.Rows.Add(tRow)
Loop
End If
End If
End Sub
Private Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
GetPatient()
End Sub
Protected Sub DeleteRecord(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lbNew As New LinkButton
Dim sResult As String = ""
Dim bResult As Boolean
lbNew = sender
bResult = PM.DeleteMultiRecord(lbNew.CommandArgument, lbNew.CommandName, Session.Item("UserID"), sResult)
If Not bResult Then
MsgBox(sResult, MsgBoxStyle.OkOnly, "Deletion was not successful")
Else
GetPatient()
End If
End Sub
Before Deleting a record, try to place a PatientID in Textbox and Delete the record, then Table will Display the records matching with the TextBox input.
The Problem is with PageLoad() method, if the TextBox is Empty And It is a Postback, then GetPatient() method will not be called. So try to modify the PageLoad() Method.
Better to remove IsPostBack condition in PageLoad().
I have searched around and it seems dynamic handler is best to be declared during PageInit. For my case, as the link button control needs to carry some values on the respective data row, it seems I can't avoid calling GetPatient to create controls.
To move on with the issue, I did a workaround by using Javascript. I created a hidLogID hidden field on ASPX page. I changed the link button to an <a> control and call a javascript function passing the dr("LogID"). The javascript function will assign the value to hidLogID and submit the page. PageLoad will call DeleteRecord()when hidLogID value is not blank. The value for hidLogID will be cleared on DeleteRecord().
Thank you for all the help!

post back to the same page not working asp.net

in my user.aspx page of any particular users account shows all other user names/images as link inside a datalist alongwith the particular users information who is logged in. now i want that if i click any of the other user links the users information should come on the same user.aspx page. i use this code on page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Session("UserName") Is Nothing Then
Response.Redirect("login.aspx")
Else
If Not (IsPostBack) Then
binddata()
binddata1()
binddata2()
End If
End If
End Sub
Sub binddata()
Dim mycommand As New SqlCommand("SELECT * FROM details where id = #id", con)
mycommand.Parameters.Add("#id", SqlDbType.Int)
mycommand.Parameters("#id").Value = Convert.ToInt32(Request.QueryString("id"))
con.Open()
Data.DataSource = mycommand.ExecuteReader
Data.DataBind()
con.Close()
End Sub
Sub binddata1()
Dim mycommand As New SqlCommand("SELECT * FROM details where id = #id", con)
mycommand.Parameters.Add("#id", SqlDbType.Int)
mycommand.Parameters("#id").Value = Convert.ToInt32(Request.QueryString("id"))
con.Open()
nameimage.DataSource = mycommand.ExecuteReader
nameimage.DataBind()
con.Close()
End Sub
Sub binddata2()
Dim mycommand As New SqlCommand("SELECT * FROM details ", con)
con.Open()
user.DataSource = mycommand.ExecuteReader
user.DataBind()
con.Close()
End Sub
and this script for datalist
<asp:DataList ID="custom" runat="server" DataKeyField="Name" RepeatColumns="1" >
<ItemTemplate>
<div><table>
<tr><asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# GetImageURL(Eval("Pic")) %>' PostBackUrl='<%# Eval("id", "user.aspx?id={0}") %>'/></tr>
<tr><td align="left" valign="top" style="width:90px"><asp:LinkButton ID="name" runat="server" ForeColor="Blue" Text='<%#Container.DataItem("Name")%>'></asp:LinkButton></td></tr>
</table></div></ItemTemplate>
</asp:DataList>
this code is working fine for first check/click. when i click one of the users it load the details of the user . but after that when i click another user it doesnot load the details of that user. i want to show : a user logged in , then there on his page there are list of other users with images. when i click any of them the details of the particular should be load in proper places. help me with this
You are checking for a first page load before perform data binding. Remove this check or check for control name that fire postback before it.
Yuriy's answer should work but another approach is to use CommandArgument instead of PostBackUrl. You will need to setup an event handler for your DataList ItemCommand. The CommandArgument value will be your ID value. Your event handler will take that ID and bind it to your data display.

asp.net vb CheckBoxList Selected from CSV

I am learning asp.net and needed to have a CheckBoxList which items will be initially selected if the are in a CSV string from a database.
I have got it working although I just wondered if I have gone about it the best way as it seemed a little long winded?
Thanks for any help provided.
ASPX
<asp:CheckBoxList ID="rh_type" runat="server" CssClass="chkbox"
RepeatLayout="Flow" CausesValidation="True">
<asp:ListItem>House</asp:ListItem>
<asp:ListItem>Flat/Apartment</asp:ListItem>
<asp:ListItem>Bungalow</asp:ListItem>
<asp:ListItem>Any</asp:ListItem>
</asp:CheckBoxList>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
CODE
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim i As Integer
Dim str_rh_type As String = "House,Bungalow"
Dim split As String() = str_rh_type.Split(","c)
For Each s As String In split
'Response.Write(s & "<br />")
For i = 0 To rh_type.Items.Count - 1
If rh_type.Items(i).Text = s Then
rh_type.Items(i).Selected = True
End If
Next
Next s
End Sub
Thanks again
J.
Your code is functional but maybe some tweaking for maintainability would help. Also not sure you necessarily need nested loops to load your drop down items.
This should be just a reference point to make your own decisions on coding practices. Certainly what works for some doesn't work for others.
Here's how I'd code this...
ASP.NET Control:
<asp:CheckBoxList ID="CheckBoxListHomeType" runat="server"
CssClass="chkbox" RepeatLayout="Flow" CausesValidation="True" />
...
ID of CheckBoxListHomeType is easy to remember and intellisense will get me the rest of the way. (or another common approach would be cblHomeType as the ID). Getting intellisense to help on a name like rh_type may be just as easy but IDs that resemble what kind of control it is can really help when maintaining code
VB.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LoadHomeTypes()
End If
End Sub
Protected Sub LoadHomeTypes()
Dim houseTypes = "House,Bungalow,Flat/Apartment,Any"
For Each houseType As String In houseTypes.Split(",")
CheckBoxListHomeType.Items.Add(New ListItem(houseType))
Next
End Sub
Keeping the logic in a separate LoadHomeTypes function can make the code more readable.
Creating a new ListItem while iterating the list of homeTypes should remove the need to iterate over the CheckBoxList items, (if you need to clear out the existing ones you can add CheckBoxListHomeType.Items.Clear() to the top of the function)
the Not Page.IsPostBack check prevents the need for loading the drop down values every postback, unless you have need for them to change.
This is the good answers , try this
Dim ds As DataSet
ds = Insertstu.searchrec(txtsearch.Text)
txtnm.Text = ds.Tables(0).Rows(0)("stuname").ToString()
txtadd.Text = ds.Tables(0).Rows(0)("stuaddress").ToString()
txtph.Text = ds.Tables(0).Rows(0)("stuph").ToString()
rdobtnsex.Text = ds.Tables(0).Rows(0)("sex").ToString()
Dim arr As String()
Dim quali As String = ds.Tables(0).Rows(0)("qualified").ToString()
arr = quali.Split(",")
Dim i As Integer
For Each itm As String In arr
For i = 0 To chkqualify.Items.Count - 1
If chkqualify.Items(i).Text = itm Then
chkqualify.Items(i).Selected = True
End If
Next
Next
''chkqualify is checkboxlist id

How do I create a nested GridView bound to parent's EntityDataSource's navigation property?

<asp:FormView DataSourceId="edsAccounts">
<ItemTemplate>
<asp:TextBox Text='<%# Eval("Email") %>' />
<asp:DataGrid ID="dgReports" DataSource='<%# Eval("Reports") %>'>
</ItemTemplate>
</asp:FormView>
<asp:EntityDataSource ID="edsAccounts" runat="server" ConnectionString="name=Entities" DefaultContainerName="Entities" EntitySetName="Accounts" EntityTypeFilter="Account" Include="Reports" />
I want the dgReports to start working.
Note that the email text box works just fine.
I indeed created seperate inner datasources, but I got another problem.
I was unable to set the Where clause to the parent's Entity's ID.
Notice that the FormView.DataItem is not accessible; it's of type EntityDataSourceWrapper which is a friend class and inaccessible.
So I created a function to deal with it by reflection.
I think it's a Microsoft bug, till they fix it, the following might be usefull to anyone who uses nested EntityDataSource controls.
Here it is:
Module Functions
Public Function GetEntity(Of TEntity As EntityObject)(ByVal entityDataSourceWrapper As Object) As TEntity
If entityDataSourceWrapper Is Nothing Then Return Nothing
Dim type = entityDataSourceWrapper.GetType()
If Not type.FullName = "System.Web.UI.WebControls.EntityDataSourceWrapper" Then Return Nothing
Dim wrapper = type.GetProperty("WrappedEntity", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
Return DirectCast(wrapper.GetValue(entityDataSourceWrapper, Nothing), TEntity)
End Function
End Module
Now in the code behind I do the following:
Protected Sub fvAccounts_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles fvAccounts.DataBound
If fvAccounts.CurrentMode <> FormViewMode.ReadOnly Then Exit Sub
Dim account As Account = GetEntity(Of Account)(fvAccounts.DataItem)
If account Is Nothing Then Exit Sub
Dim edsReports As EntityDataSource = fvAccounts.Row.FindControl("edsReports")
edsReports.Where = "it.Account.AccountId = " & account.AccountId
gvReports.DataBind()
End Sub
Note the hierarchy in the model: Account has many reports.

Resources