get first name from user table master_page - asp.net

I'm using a masterPage.master to get the login info for my application. When the user login in with username/password it shows the username as logged in and I would like it to be more personal by pulling the firstname only. How can I do this, I tried all I know, I'm new to ASP.Net.
masterpage: `
<div id="login">
<asp:LoginView ID="MasterLoginView" runat="server">
<LoggedInTemplate>
Welcome:
<asp:LoginName ID="MasterLoginName" runat="server" Font-Bold="True" />
</LoggedInTemplate>
<AnonymousTemplate>
Welcome: Guest...
</AnonymousTemplate>
</asp:LoginView>
</div>
<div id="login2">
<asp:LoginStatus ID="LoginStatus1" runat="server"
LogoutAction="Redirect" LogoutPageUrl="access/LoggedOut.aspx"
LoginImageUrl="images/login.jpg" LogoutImageUrl="images/logout.jpg" LoginText=""
LogoutText="" />
</div>`
Login.aspx:
<asp:Label ID="Login1" runat="server" Text="Label" ForeColor="White"></asp:Label>
<p>Username:
<asp:TextBox ID="txtusername" runat="server" Width="150px"></asp:TextBox></p>
<p>Password:
<asp:TextBox ID="txtpassword" runat="server" Width="150px" TextMode="Password"></asp:TextBox>
</p>
<asp:ImageButton ID="LoginButton" runat="server" ImageUrl="../images/lsubmit.png"
OnClick="LoginBtnClick" ValidationGroup="a" ToolTip="Submit" ImageAlign="AbsBottom" />
login.aspx.vb
Partial Public Class Login
Inherits System.Web.UI.Page
Private con As New SqlConnection()
Private adp As SqlDataAdapter
Private ds As New DataSet()
Protected Sub LoginBtnClick(sender As Object, e As System.EventArgs) Handles LoginButton.Click
Dim con As New SqlConnection("Data Source=HQDANA3A413VDB1;Initial Catalog=Sigar;User ID=Sigar_Admin;Password=$Jzpoj^6z>%y9E")
con.Open()
' here with the help of this sql query i am matching the username and password of //the user.
Dim cmd As New SqlCommand()
cmd.CommandText = "select * from Users where username=#username and password=#password"
cmd.Connection = con
' here i am passing the parameter of username and password
cmd.Parameters.Add("#username", SqlDbType.VarChar, 50).Value = txtusername.Text
cmd.Parameters.Add("#password", SqlDbType.VarChar, 50).Value = txtpassword.Text
Dim firstName As New SqlParameter("#firstname", SqlDbType.VarChar, 50, ToString)
firstName.Value = ToString()
cmd.Parameters.Add(firstName)
Dim dr As SqlDataReader = cmd.ExecuteReader()
' here i am using hasrows to check the correct user. If the username and the password
'//of the user will be mathed with the database then it will be go to the checkuser.aspx //page otherwise it prints the message wrongusername or password
If dr.HasRows Then
dr.Read()
' here i am creating a formauthentication ticket that will be use in the whole //application.
'This is the main part of the formauthentication security, inside dr[2] //there is a role of the user
Dim tkt As New FormsAuthenticationTicket(1, txtusername.Text.ToUpper, DateTime.Now, DateTime.Now.AddHours(3), False, dr(2).ToString(), _
FormsAuthentication.FormsCookiePath)
' here i am enctypt the ticket. With the encryption of this ticket it will encrypt the //username
Dim st As [String] = FormsAuthentication.Encrypt(tkt)
' here i am creat a cookie that will we used inside the whole application
Dim ck As New HttpCookie(FormsAuthentication.FormsCookieName, st)
Response.Cookies.Add(ck)
' Validate the user against the Membership framework user store
'If Membership.ValidateUser(txtusername.Text, txtpassword.Text) Then
' Log the user into the site
'FormsAuthentication.RedirectFromLoginPage(txtusername.Text, RememberMe.Checked)
Response.Redirect("checkuser.aspx")
Else
LabelFailedAuthentication.Visible = True
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
CancelButton.Attributes.Add("onClick", "javascript:history.back(); return false;")
End Sub
End Class

You can use the LoginStatus control to set the logout text, assuming that the first name is the first part of your Username (in Master):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.LoginStatus1.LogoutText = "Logout: " & GetUserName()
End Sub
Public Function GetUserName() As String
If HttpContext.Current.User.Identity.IsAuthenticated Then
If ViewState("UserName") Is Nothing Then
Dim user As MembershipUser = Membership.GetUser()
' split user-name, assuming that the first part is the firstname '
Dim nameParts = user.ToString().Split()
ViewState("UserName") = nameParts(0)
End If
Return DirectCast(ViewState("UserName"), String)
Else
Return String.Empty
End If
End Function

Related

ASP.net datatable is returning no values

i hope you can help with my issue. I'm trying to fill out a form from my database using a datatable. All seems to work fine but i get no data returned. Can anyone explain why? I've looked at the debug and there seems to be no errors and nothing looks like its failed. Here's my code behind (vb.net)
Imports System.Data
Imports System.Data.SqlClient
Imports System.Net.Mail
Partial Class _Default
Inherits System.Web.UI.Page
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim constr As String = ConfigurationManager.ConnectionStrings("conn").ConnectionString
Dim connection As New SqlConnection(constr)
connection.Open()
Dim sqlCmd As New SqlCommand("SELECT * from tblContent WHERE CID = #ID", connection)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#ID", Request.QueryString("ID"))
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
ID.Text = dt.Rows(0)("CID").ToString
TextBox2.Text = dt.Rows(0)("Heading").ToString
TextBox1.Text = dt.Rows(0)("ContText").ToString
Label2.Text = dt.Rows(0)("Location").ToString
End If
connection.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
getData(Me.User.Identity.Name)
End If
End Sub
Presentation layer:
<h2><asp:Label ID="Label2" runat="server" Text=""></asp:Label></h2>
<asp:TextBox ID="ID" runat="server" Visible="false"> </asp:TextBox><br />
<asp:Label ID="Label3" runat="server" Text="Heading" CssClass="label"></asp:Label>
<asp:TextBox ID="TextBox2" TextMode="SingleLine" Text="" runat="server"></asp:TextBox><br />
<asp:Label ID="Label1" runat="server" Text="Content" CssClass="label"></asp:Label><br />
<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server"></asp:TextBox>
I'm passing through the ID from another page via the query string (ID=5 as an example). There is data in my database and all labels/textboxes have the right IDs etc. I just can see what's wrong?
Thanks!
You could try to pass the correct type instead of string:
Using sqlDa As New SqlDataAdapter(sqlCmd)
Dim idParam = new SqlParameter("#ID", SqlDbType.Int)
Dim id As Int32
If Not Int32.TryParse(Request.QueryString("ID"), id) Then Throw New Exception("Not a valid ID-parameter!")
idParam.Value = id
sqlDa.SelectCommand.Parameters.Add(idParam)
sqlDa.Fill(dt)
End Using
By the way, also use the Using-statement for the connection. As an aside, you don't need to open/close the connection with SqlDataAdapter.Fill(table) since that is done automatically.

Dynamically created buttons not calling function on postback

In my visual basic web application I have a list of generated buttons that are supposed to allow the download of a file on click.
I had the example working with generated buttons on pageload, but all of a sudden the download function stopped getting called on post back, and now all the button click does (for any of the buttons) is cause a page post back.
My code:
Public folder As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
folder = "Main"
PopulateFiles(folder)
End If
End Sub
Protected Sub PopulateFiles(ByVal folder As String)
Dim myConnection As SqlConnection
Dim conString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim myCommand As SqlCommand
Dim myDataReader As SqlDataReader
Dim text As String
Dim size As Decimal
Dim name As String
Dim type As String
Dim id As Integer
folderName.Text = folder
container.Controls.Clear()
myConnection = New SqlConnection(conString)
myConnection.Open()
myCommand = New SqlCommand("Uploads_GetAllFiles", myConnection)
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Parameters.AddWithValue("#folder", folder)
Try
myDataReader = myCommand.ExecuteReader()
If myDataReader.HasRows Then
Do While myDataReader.Read()
name = myDataReader.Item("Name")
type = myDataReader.Item("Type")
id = myDataReader.Item("File_ID")
size = Math.Round(myDataReader.Item("Size") / 1000, 2)
container.Controls.Add(New LiteralControl("<div class='newRow'>"))
text = "<div class='fileName'>" & name & "</div>"
container.Controls.Add(New LiteralControl(text))
text = "<div class='fileType'>" & type & "</div>"
container.Controls.Add(New LiteralControl(text))
text = "<div class='fileSize'>" & size.ToString() & "kb</div>"
container.Controls.Add(New LiteralControl(text))
container.Controls.Add(New LiteralControl("<div class='fileDownload'>"))
Dim newBtn As New Button
newBtn.ID = "link" & id
newBtn.Text = "Download"
newBtn.CssClass = "newbie"
AddHandler newBtn.Click, AddressOf Retreive_Doc
newBtn.CommandArgument = id
container.Controls.Add(newBtn)
container.Controls.Add(New LiteralControl("</div>"))
container.Controls.Add(New LiteralControl("<div class='fileDelete'>"))
Dim newDelBtn As New Button
newDelBtn.ID = "delete" & id
newDelBtn.Text = "Delete"
newDelBtn.CssClass = "delBtn"
AddHandler newDelBtn.Click, AddressOf Retreive_Xls
newDelBtn.CommandArgument = id
container.Controls.Add(newDelBtn)
container.Controls.Add(New LiteralControl("</div>"))
container.Controls.Add(New LiteralControl("</div>"))
Loop
End If
Catch ex As Exception
MsgBox(ex.ToString())
Finally
myConnection.Close()
End Try
End Sub
Protected Sub Retreive_Doc(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
Dim button As Button = sender
Dim id As Integer = button.CommandArgument
Dim cmd As SqlCommand = New SqlCommand("Uploads_GetFile")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", id)
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Sub
I could show the functions called from this function, but the initial function isn't even being called so I'm not sure there is a point.
My HTML is as follows:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:FileUpload ID="upload1" runat="server" /><asp:Button ID="test1" runat="server" Text="Upload" />
<asp:TextBox ID="folderTag" runat="server" ></asp:TextBox>
<asp:Button ID="search" runat="server" Text="Search" />
<asp:Label ID="folderName" runat="server">General</asp:Label><br />
<div id="navContainer" runat="server">
</div>
<div id="hiddenContent">
<asp:LinkButton ID="LinkButton1" CssClass="hide" runat="server" OnClick = "Retreive_Doc">Download Doc</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" CssClass="hide" runat="server" OnClick = "Retreive_Xls">Download xls</asp:LinkButton>
</div>
<div id="container" runat="server">
</div>
</form>
As I said before. This was working a few days ago and through the course of adding some other functionality somehow I lost it.
I'm unsure of why it posts back without calling any function.
Thanks for any help!
You need to recreate the controls with same ID in post back if you created them dynamically. Otherwise, they will disappear after postback.
Remove If Not IsPostBack Then in page load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
folder = "Main"
PopulateFiles(folder)
End Sub
Another thought:
Is there a reason not to use CommandEvent instead of Click event if you want CommandArgument?
Again, Is there a reason not to use PlaceHolder instead of <div id="container" runat="server">?
AddHandler newBtn.Command, AddressOf Retreive_Doc
newBtn.CommandArgument = id
....
protected void Retreive_Doc(object sender, CommandEventArgs e)

DropDownList after postback all values/index lost

I'm running into a little problem with a gridview and a dropdownlist. I can get the dropdownlist to load initially, but when it autopostback's it returns with no value. I am populating the dropdownlist in the RowEditing sub. I'm guessing that I must somehow rebind in the RowDataBound sub, but don't know how to go about it. If I try to find the control's SelectedValue I end up with nothing.
VB Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
bindGridView()
End If
End Sub
'Menu Click
'bindGridView
Public Sub bindGridView(Optional ByVal sortExp As String = "", Optional ByVal sortDir As String = "")
Dim strConnString As String = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString
Dim conn As SqlConnection = New SqlConnection(strConnString)
conn.Open()
Dim strProgramNumber As String = 5
Dim strRecordType As String = "Input Source"
Dim strProgramInformation As String = "\\path\to\file"
Dim sql As String
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
If sortExp <> String.Empty Then
sortExp = (sortExp & " " & sortDir).ToString
sql = "SELECT tblPrgTrackPrograms.ProgramNumber, " & _
"tblPrgTrackPrograms.ProgramName, " & _
"tblPrgTrackPrograms.ProgramStatus, " & _
"tblPrgTrackProgramDocumentation.RecordType, " & _
"tblPrgTrackProgramDocumentation.ProgramInformation " & _
"FROM tblPrgTrackPrograms INNER JOIN tblPrgTrackProgramDocumentation ON " & _
"tblPrgTrackPrograms.ProgramNumber = tblPrgTrackProgramDocumentation.ProgramNumber ORDER BY " & _
"#sortExp"
cmd.Parameters.AddWithValue("sortExp", sortExp)
Else
sql = "SELECT tblPrgTrackPrograms.ProgramNumber, " & _
"tblPrgTrackPrograms.ProgramName, " & _
"tblPrgTrackPrograms.ProgramStatus, " & _
"tblPrgTrackProgramDocumentation.RecordType, " & _
"tblPrgTrackProgramDocumentation.ProgramInformation " & _
"FROM tblPrgTrackPrograms INNER JOIN tblPrgTrackProgramDocumentation ON " & _
"tblPrgTrackPrograms.ProgramNumber = tblPrgTrackProgramDocumentation.ProgramNumber"
End If
cmd.CommandText = sql
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(cmd)
mySQLAdapter.SelectCommand.Connection = conn
mySQLAdapter.Fill(myDataSet)
conn.Close()
gvProgramDetails.DataSource = myDataSet
gvProgramDetails.DataBind()
End Sub
'ProgramDetails Load
Protected Sub gvProgramDetails_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvProgramDetails.Load
bindGridView()
End Sub
'ProgramDetails Paging
Protected Sub gvProgramDetails_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvProgramDetails.PageIndexChanging
gvProgramDetails.PageIndex = e.NewPageIndex
bindGridView()
End Sub
'ProgramDetails Sorting
Protected Sub gvProgramDetails_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvProgramDetails.Sorting
Dim SortDirection As String
If Session("SortDirection") = vbNullString Then
Session("SortDirection") = "DESC"
Else
SortDirection = Session("SortDirection").ToString
If SortDirection = "ASC" Then
SortDirection = "DESC"
ElseIf SortDirection = "DESC" Then
SortDirection = "ASC"
Else
SortDirection = "ASC"
End If
bindGridView(e.SortExpression, Session("SortDirection"))
'Need to store sort info in view state
Session("SortDirection") = SortDirection
End If
End Sub
'ProgramDetails RowEditing
Protected Sub gvProgramDetails_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvProgramDetails.RowEditing
Dim lbl As Label = CType(gvProgramDetails.Rows(e.NewEditIndex).FindControl("lblRecordType"), Label)
Dim strValue As String = lbl.Text
gvProgramDetails.EditIndex = e.NewEditIndex
bindGridView()
Dim row As GridViewRow = gvProgramDetails.Rows(e.NewEditIndex)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("CSPaperWEBConnectionString").ConnectionString
Dim ddlRecordType As DropDownList = CType(row.FindControl("ddlRecordType"), DropDownList)
Dim conn As SqlConnection = New SqlConnection(strConnString)
conn.Open()
Dim sql As String
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
sql = "select RecordType from [tblPrgTrackValidRecordTypes] "
cmd.CommandText = sql
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(cmd)
mySQLAdapter.SelectCommand.Connection = conn
mySQLAdapter.Fill(myDataSet)
conn.Close()
If ddlRecordType IsNot Nothing Then
ddlRecordType.DataTextField = "RecordType"
ddlRecordType.DataValueField = "RecordType"
ddlRecordType.DataSource = myDataSet
ddlRecordType.SelectedValue = strValue
ddlRecordType.DataBind()
End If
End Sub
Protected Sub gvProgramDetails_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvProgramDetails.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ctrl As Control = e.Row.FindControl("ddlRecordType")
If ctrl IsNot Nothing Then
Dim ddlRecordType As DropDownList = ctrl
MsgBox(ddlRecordType.SelectedValue)
End If
End If
End Sub
'ProgramDetails RowUpdating
Protected Sub gvProgramDetails_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvProgramDetails.RowUpdating
Dim ddlRecordType As DropDownList = gvProgramDetails.Rows(e.RowIndex).FindControl("ddlRecordType")
MsgBox(ddlRecordType.SelectedValue)
gvProgramDetails.EditIndex = -1
bindGridView()
End Sub
'ProgramDetails RowCancelingEdit
Protected Sub gvProgramDetails_RowCancelingEdit1(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles gvProgramDetails.RowCancelingEdit
gvProgramDetails.EditIndex = -1
bindGridView()
End Sub
'ProgramDetails RowDeleting
Protected Sub gvProgramDetails_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvProgramDetails.RowDeleting
Dim strConnString As String = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString
Dim conn As SqlConnection = New SqlConnection(strConnString)
conn.Open()
Dim strProgramNumber As String = 5
Dim strRecordType As String = "Input Source"
Dim strProgramInformation As String = "\\path\to\file"
Dim sql As String = "delete from tblPrgTrackProgramDocumentation where ProgramNumber = #ProgramNumber and RecordType = #RecordType and ProgramInformation = #ProgramInformation"
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = conn
cmd.CommandText = sql
cmd.Parameters.AddWithValue("ProgramNumber", strProgramNumber)
cmd.Parameters.AddWithValue("RecordType", strRecordType)
cmd.Parameters.AddWithValue("ProgramInformation", strProgramInformation)
cmd.ExecuteNonQuery()
cmd.Dispose()
bindGridView()
End Sub
ASP front end
<ajx:UpdatePanel ID="ajaxpanel" runat="server">
<ContentTemplate>
<asp:GridView ID="gvProgramDetails" runat="server" AutoGenerateColumns="False"
CssClass="gridview" DataKeyNames="ProgramNumber" AllowPaging="True" PageSize="3" AllowSorting="True" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record');"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
<ControlStyle CssClass="button delete" />
</asp:TemplateField>
<asp:CommandField ControlStyle-CssClass="button save" ShowEditButton="True">
<ControlStyle CssClass="button save" />
</asp:CommandField>
<asp:BoundField DataField="ProgramNumber" HeaderText="ProgramNumber"
InsertVisible="False" ReadOnly="True" SortExpression="ProgramNumber" />
<asp:BoundField DataField="ProgramName" HeaderText="ProgramName" ReadOnly="True"
SortExpression="ProgramName" />
<asp:BoundField DataField="ProgramStatus" HeaderText="ProgramStatus" ReadOnly="True"
SortExpression="ProgramStatus" />
<asp:TemplateField HeaderText="RecordType" SortExpression="RecordType">
<EditItemTemplate>
<asp:DropDownList ID="ddlRecordType" runat="server" autopostback="True">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblRecordType" runat="server" Text='<%# Bind("RecordType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProgramInformation" HeaderText="ProgramInformation"
SortExpression="ProgramInformation" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:WEBConnectionString %>"
SelectCommand="SELECT * FROM [tblPrgTrackValidRecordTypes]"></asp:SqlDataSource>
</ContentTemplate>
</ajx:UpdatePanel>
For those of you who answer drag the control in from the toolbox, create datasource, and set bind("RecordType") please don't. I've tried it that way and the value would always post back with whatever Recordtype was. So unless if you can solve that version of this gridview don't use drag/drop control solution. I'm scratching my brain to solve this one.
Update
I created under App_Code Process/ddlRecordType.vb
Imports Microsoft.VisualBasic
Namespace processes.ProgramTrack.dllRecordType
Public Class ddlRecordType
Public Sub ddlRecordType()
End Sub
Public Function GetRecords() As DataSet
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
conn.ConnectionString = ConfigurationManager.ConnectionStrings("WEBConnectionString").ConnectionString.ToString
cmd.CommandText = "select RecordType from [tblPrgTrackValidRecordTypes] "
cmd.Connection = conn
Dim myDataSet As New DataSet()
Dim mySQLAdapter As New SqlDataAdapter(cmd)
mySQLAdapter.Fill(myDataSet)
Return myDataSet
End Function
End Class
End Namespace
My markup then looks like this.
<asp:DropDownList ID="ddlRecordType" DatasourceID="odsRecordType" DataTextField="RecordType" DataValueField="RecordType" runat="server" autopostback="True" > </asp:DropDownList>
<asp:ObjectDataSource ID="odsRecordType" runat="server" TypeName="processes.ProgramTrack.dllRecordType.ddlRecordType" SelectMethod="GetRecords"></asp:ObjectDataSource>
Then I get the same problem as before about the DDL not maintaining it's value at postback. Should I start a new Question or continue with this one?
Update to fix the DDL not maintaining. Disable Viewstate for the gridview.
<asp:GridView ID="gvProgramDetails" runat="server" AutoGenerateColumns="False" CssClass="gridview"DataKeyNames="ProgramNumber" AllowPaging="True" PageSize="10" EnableViewState="False" AllowSorting="True">
Try creating an objectDataSource for the DDL, and use that. The problem is that the DDL has to be initialized at page load, or on page init, OR via a DataSource control. If you weren't using the Ajax UpdatePanel (go ahead, take it out, watch your code work, it should anyways) then you would be able to do it like this.
If you'll introduce an ObjectDataSource (and you can pass parameters to it too) then you should end up with what you want.
Edit:
I'm going to provide code from a project of mine, so that you can see how I'm using it. This code will not be perfect to your needs, but will show you how to do what you want.
namespace Appropriate.Namespace.Here {
public class MyType {
public List<KeyValuePair<string, string>> GetRoles() {
List<KeyValuePair<string, string>> l = new List<KeyValuePair<string, string>>();
l.Add( new KeyValuePair<string, string>( "Level1", "Analyst" ) );
l.Add( new KeyValuePair<string, string>( "Level2", "Customer Service" ) );
l.Add( new KeyValuePair<string, string>( "Level3", "Customer Service Manager" ) );
l.Add( new KeyValuePair<string, string>( "Level4", "Full-Access User" ) );
l.Add( new KeyValuePair<string, string>( "Level5", "Super User" ) );
return l;
}
}
}
<asp:DropDownList ID="cmbRoles" runat="server" AutoPostBack="False" DataSourceID="odsRoles" DataTextField="Value" DataValueField="Key" />
<asp:ObjectDataSource ID="odsRoles" runat="server" TypeName="Appropriate.Namespace.Here.MyType" SelectMethod="GetRoles" />
Notice how the namespace and typename work together to give me the SelectMethod? I'm not providing an override on the select parameters, altho you could. You would do that in the page backing code, and I could give some insight on that as well, but I'm trying to not be entirely overly complex.
Notice how I'm returning a List from the method? And I'm just defining it in that method? You could just as easily do a database call there.

ASP.net: GridView columns repeating after paging

I have a GridView that has it's columns added dynamically in codebehind. I've added paging to the GridView, and it works, but when it goes to the next page, it adds the columns again.
So the GridView starts out with 2 columns (Last Name and First Name) added from codebehind. Then I go to it's next page, and it properly loads the next page of results, but now with 4 columns (Last Name, First Name, Last Name, First Name).
What am I doing wrong here?
Here's the code for the GridView:
<asp:GridView id="GridView3" runat="server" AutoGenerateColumns="False"
EmptyDataText="There are no data records to display."
AllowPaging="True"
OnPageIndexChanging="GridView3_PageIndexChanging"
CssClass="GridViewStyle" GridLines="None" Width="100%">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="EmplID"
DataNavigateUrlFormatString="EmployeeProfile.aspx?EmplID={0}"
DataTextField="EmplID"
DataTextFormatString= "<img src='Images/icons/document-search-result.png' alt='View'/> <u>View</u>" >
<ControlStyle CssClass="titleLinksB" />
<ItemStyle Wrap="False" />
</asp:HyperLinkField>
</Columns>
</asp:GridView>
Here's the code for the codebehind:
Private Sub loadDynamicGrid()
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim lastName As String
Dim linkText As String
lastName = Request.QueryString("lastName")
connetionString = ConfigurationManager.ConnectionStrings("dbConnectionString").ConnectionString.ToString()
sql = "SELECT * FROM [EmployeeList] Where [lastname] like '" & lastName & "%' order by lastname"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
Dim curLastName As New BoundField
curLastName.HeaderText = "Last Name"
curLastName.DataField = "LastName"
GridView3.Columns.Insert(0, curLastName)
Dim curFirstName As New BoundField
curFirstName.HeaderText = "First Name"
curFirstName.DataField = "FirstName"
GridView3.Columns.Insert(1, curFirstName)
GridView3.Visible = True
GridView3.DataSource = ds
GridView3.DataBind()
adapter.Dispose()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
And finally the Paging code:
Protected Sub GridView3_PageIndexChanging(ByVal sender As [Object], ByVal e As GridViewPageEventArgs)
GridView3.PageIndex = e.NewPageIndex
GridView3.DataBind()
End Sub
Any help is greatly appreciated!
I assume that you're calling loadDynamicGrid on every postback and not only If Not Page.IsPostBack.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
loadDynamicGrid()
End If
End Sub

dynamically build html table on page load

Edit for vhinn
I want it to look like this:
I am trying to build an html table dynamically on pageload with variables from a database.
this is an example strictly html http://jsfiddle.net/jdv590/daCum/1/
code:
Private Sub brothersgird()
Dim html As New StringBuilder
Dim sql As String = "select Name, Hometown, Picture, Class from brothers",
connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;",
conn As New OleDbConnection(connstring),
myCommand As New OleDbCommand(sql, conn),
namevar As String,
classvar As String,
hometownvar As String
Dim x As Integer = 1
conn.Open()
Dim dr As OleDbDataReader = myCommand.ExecuteReader
html.Append("<table>")
Do While dr.Read
' imagevar = dr("Picture")
namevar = dr("Name")
classvar = dr("Class")
hometownvar = dr("Hometown")
html.Append("<tr>")
Do While x < 4
html.Append("<td><p>" & namevar & "<br /> Hometown: " & hometownvar & "<br /> Class: " & classvar & "</p></td>")
x = x + 1
Loop
html.Append("</tr>")
x = 0
Loop
html.Append("</table>")
dr.Close()
conn.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
brothersgird()
'write to panel maybe with this idea:
seniorpanel.html=html ???
End Sub
aspx side:
<asp:Panel ID="seniorpanel" runat="server">
</asp:Panel>
in your markup:
<asp:Panel ID="seniorpanel" runat="server">
<asp:GridView ID="brothersgird" runat="server" ShowHeader="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<p>
<%# Eval("Name")%><br />
Hometown:
<%# Eval("Hometown")%><br />
Class:
<%# Eval("Hometown")%>
</p>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
code-behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
brothersgird.DataSource = SelectBrothers()
brothersgird.DataBind()
End If
End Sub
Private Function SelectBrothers() As DataTable
Dim sql As String = "select Name, Hometown, Picture, Class from brothers"
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=~/App_Data/Members.accdb;Persist Security Info=False;"
Dim conn As New OleDbConnection(connstring)
Dim ds As New DataSet
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand(sql, conn)
adapter.Fill(ds)
Return ds.Tables(0)
End Function
You familiar with DataGrids?
Client Side:
<asp:DataGrid runat="server" id="dataTable">
</asp:DataGrid>
Server Side:
//Get your data table from the database - let's say the variable is called dt
dataTable.DataSource = dt
dataTable.DataBind()
There is a lot more you can do with datagrids, but this should be enough to get you started if you decide to go this route.
Are you asking how to do this in javascript if you already have the data? If so an example would be kinda like this:
var row = document.createElement("TR");
var th1 = document.createElement("TH");
row.appendChild(th1);

Resources