Hyperlink in DataField of GridView ASP.net - asp.net

I have a GridView with rows and lines. In lines i've put names (e.g. John, Jack, Paul,...) and in the rows the statistics (e.g work hours, salary, status,...). I don't know how to set an hyperlink on the name in order to open a page with the entire profile of the person selected. I want to click on Paul and be redirected to another page with the entire profile plus the photo and other info. Each name must have a different hyperlink. I tried to do it through Access directly but didn't work.
Thank You
Richard

you should use this line of code in the gridview.Add the hyperlink in gridview and edit this code to make it functioning.
<asp:hyperlinkfield text="Name?"
datanavigateurlfields="Id"
datanavigateurlformatstring="~\Persondetails.aspx?id={0}" //passing the Id to new page
headertext="Name"
target="_blank" />
at the second page you should write the code like this to make sure display the selected nama display all detail in second page.
Dim nameID As String
nameID = Request.QueryString("id")
Dim nameqstring As Integer = Convert.ToInt32(nameID)
to display data from selected second page use this one
Using sqlComm As New MySqlCommand()
sqlComm.Connection = sqlConn
With sqlComm
.CommandText = "select * From table where NameId=#nameId"
.Parameters.AddWithValue("#nameId", nameID)
Try
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
Label1.Text = sqlReader("Name").ToString()
Label2.Text = sqlReader("Job").ToString()
Label3.Text = sqlReader("Salary").ToString()
Label4.Text = sqlReader("Workhours").ToString()
Label5.Text = sqlReader("Status").ToString()
End While End Using End Using
hope this can help you alot.

Related

vb.net: Why does Email-form return the ID of the value in a dropdown list as oppose to the text

I have a form written in vb.net. Upon clicking the submit button, the information in the form is emailed over to a specific email address. The form successfully captures the information from my text-box controls, but for the Dropdownlist controls, it brings back the ID of the list-item as oppose to the text.
Hypertext:
<asp:DropDownList ID="ddlCarrier" runat="server" DataTextField="Carrier_Name"
DataValueField="Carrier_ID">
</asp:DropDownList>
The original developer has it set to where the list-items are bind to the dropdown-list via the following code snippet, which uses a global variable: "dl" to access another function stored in a dataLayer file:
Dim dl As New DataLayer
Me.ddlCarrier.DataSource = dl.GetCarriers
Me.ddlCarrier.DataBind()
Me.ddlCarrier.DataTextField = "carrier_name"
Me.ddlCarrier.DataValueField = "carrier_id"
...Function that is stored in the dataLayer file:
Public Function GetCarriers() As DataTable
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ShipperNotificationConnectionString").ConnectionString
Dim myCommand As SqlDataAdapter
myCommand = New SqlDataAdapter("SELECT carrier_id,carrier_code,carrier_name,active from Carrier", connectionString)
Dim dtCarriers As DataTable = New DataTable()
myCommand.Fill(dtCarriers)
Return dtCarriers
End Function
lastly, the code snippet used the in the email function:
"<tr><td><b>Carrier:</b>" + ddlCarrier.SelectedValue.ToString() + "</td></tr>" & _
...The dropdownlist successfully populates the text, but when submitted via the form, I get the ID instead of the text itself. Could I get some help as to what I'm missing?
Instead of ddlCarrier.SelectedValue try ddlCarrier.SelectedItem.Text

asp.net grid view and dataList

I need help with a part of my website I'm coding. I have a listBox_Products which is populated with sqlServerDataSource. When I click on a product, it will display a corresponding picture along a gridview with productPrice and productName. The gridview is databound programmatically in the codebehind, on the indexChange event. I have a button, addToShoppingCart. On the button_Click event, I want to add the item the user chose to the shopping cart (it's on the same page), I have a second gridView, which received the item the user chose and displays it. This is where I'm stuck. I know I can't append to gridview, and I know it has to be databound. My logic is this: get the first item user chooses, add it to a datatable, insert into second gridview. Now if the user chooses another product, same logic, except this time, I would add a new row, and add the new data to the new row, keeping old row as well. Problem is I can't figure out how to do this. I'm not very experienced in datatable.
This is my code behind.
This is my code to get the product from sql server:
Private Sub GetProducts()
Dim TechShopConnectionString As String = ConfigurationManager.ConnectionStrings("Zapata_IT_DataBaseConnectionString").ConnectionString
Dim TechCon As New SqlConnection(TechShopConnectionString)
Dim TechCmd As New SqlCommand()
Dim index As Integer = ListBox_Products.SelectedIndex()
TechCmd.CommandType = CommandType.StoredProcedure
TechCmd.CommandText = "GetAllProductInformationByID"
TechCmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = index
TechCmd.Connection = TechCon
Try
TechCon.Open()
GridView2.EmptyDataText = "No Records Found"
GridView2.DataSource = TechCmd.ExecuteReader()
GridView2.DataBind()
Catch ex As Exception
Throw ex
Finally
TechCon.Close()
TechCon.Dispose()
End Try
End Sub
This is my code to add item to the second gridview:
Protected Sub Button_AddToCart_Click(sender As Object, e As EventArgs) Handles Button_AddToCart.Click
Dim conn As SqlConnection = Nothing
Dim index As Integer = ListBox_Products.SelectedIndex()
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("Zapata_IT_DataBaseConnectionString").ConnectionString
conn = New SqlConnection(connString)
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "GetAllProductInformationByID"
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = index
cmd.Connection = conn
conn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dr2 As DataRow
dataTableCheckOut.NewRow()
dataTableCheckOut.Load(dr, LoadOption.OverwriteChanges)
GridView_CheckOut.DataSource = dataTableCheckOut
GridView_CheckOut.DataBind()
Catch ex As SqlException
Catch ex As Exception
Finally
conn.Close()
End Try
' Enter code here
As you can see I'm pretty lost. I know the logic is fine, but I cant figure out the code.
Any help would be appreciated.
If you want to keep the information about what is in the users cart from page to page (which you should want to), you should be saving the items in the users cart to the database. If you go to Amazon.Com, add something to your cart, then come back later, even on another compter, you can see the items in your cart, based on your login.
Since you know how to read data from the database, this should be easy for you. Just add the info to this new cart table and read it when you need it. Maybe every page shows the number of items and you just need the count but when viewing the cart of checking out, you need to show all the info.

Populating dropboxes with SQL data

I have a few more questions regarding my latest project. Ive felt like I have made some pretty good strides over the last couple days, but I am still struggling on a few of the core concepts of the SQL libraries, namely reading from specific columns and deleting entire rows.
Over the last week I was able to build a webform, save excel files to the server, open those files and export data into specific SQL tables, and bind the data to specific data grids depending on what the user chooses through a dropdown.
What I would like to accomplish is: Dynamic population of another dropdown depending on what the user chooses from the first drop down. More specifically, I have 4 tables, in the first column of each table I have serial numbers, if the user chooses Table2 in the first drop down, I would like the second dropdown to display all the serial numbers from column1 of Table2. Then if the user choose a specific serial number from the second drown down it populates a datagrid with columns 1-5 of that related row.
The second part is to create a delete button that the user can push after the information is displayed in the datagrid, that deletes the entire row of the serial number entry from that table.
This is what I have managed to Frankenstein together from other examples:
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As System.EventArgs)
DropDownList2.Enabled = True 'its remains disabled until the user selects something from the first box
Using con As New SqlClient.SqlConnection
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=" & AppPath & "App_Data\DeviceDatabase.MDF;Integrated Security=True;User Instance=True;"
Using cmd As New SqlClient.SqlCommand
cmd.Connection = con
End Using
Dim cmdSQL As New SqlCommand()
cmdSQL.CommandType = Data.CommandType.Text
cmdSQL.CommandText = "SELECT Fieldname1 FROM " & """" & DropDownList1.SelectedItem.ToString & """" 'Im pretty sure this isnt right, and the reason I use """"" is because some of the items in the dropdown have spaced words.
Dim adptSQL As New SqlClient.SqlDataAdapter(cmdSQL)
Dim myDataSet As New DataSet()
adptSQL.Fill(myDataSet)
With myDataSet.Tables(DropDownList1.SelectedIndex) 'I think this is right
For rowNumber As Integer = 0 To .Rows.Count - 1
With .Rows(rowNumber)
DropDownList2.Items.Add(col1.rowNumber) 'This is obviously not working
End With
Next
End With
End Using
End Sub
Then, Im not quite sure how to populate the data table with the row that was selected, though currently I am able to do the entire table with using:
Private Sub GenTables(ByVal DropList As Object)
If DropList.SelectedIndex = 0 Then
GridView1.DataSourceID = Nothing
ElseIf DropList.SelectedIndex = 1 Then
GridView1.DataSourceID = "SqlDataSource1"
ElseIf DropList.SelectedIndex = 2 Then
GridView1.DataSourceID = "SqlDataSource2"
ElseIf DropList.SelectedIndex = 3 Then
GridView1.DataSourceID = "SqlDataSource3"
ElseIf DropList.SelectedIndex = 4 Then
GridView1.DataSourceID = "SqlDataSource4"
End If
GridView1.DataBind()
End Sub
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DeviceDatabaseConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:DeviceDatabaseConnectionString1.ProviderName %>"
SelectCommand="SELECT [Device:] AS column1, [SWversion:] AS column2, [Date:] AS column3, [Tester:] AS column4, [Wifi Preferred InCov:] AS column5 FROM [Galaxy Nexus]">
</asp:SqlDataSource>
'there are 3 more of these.
But I have these tables "hard coded" into the application, I can't obviously do this with every single table row. So how do I populate a datagrid without setting a SQLDataSource ahead of time in asp?
And lastly deleting the row that relates to the information displayed in the datagrid on the click of a button. If if can get a little help with the first part, Im sure I can figure out the second part.
So pretty much what I am asking is: how to populate a drop down with all the items from Coloumn1? and how to populate a datagrid from a specific row?
Any and all help is always greatly appreciated. Thanks Guys
Zach
EDIT
hmm I think I was making this a ton harder then it had to be, right now I am working with this:
Protected Sub BindDrop_Click(sender As Object, e As System.EventArgs)
DropDownList2.DataSourceID = "SqlDataSource5"
DropDownList2.DataBind()
End Sub
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:DeviceDatabaseConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:DeviceDatabaseConnectionString1.ProviderName %>"
SelectCommand="SELECT [Device:] AS column1 FROM [Galaxy Nexus]">
Its not quite right but its closer and in 1/10th the lines
alright guys i figured it out, I needed to use the ExecuteReader function (which crazily enough I couldnt find one article in auto population that uses this method). Hopefully in writing/answering this I make someone's life much easier.
Protected Sub DropDownList2_SelectedIndexChanged(sender As Object, e As System.EventArgs)
DropDownList3.Enabled = True
DropDownList3.Items.Clear()
Dim newsqlcommand As String = "Select [SWversion:] FROM " & """" & DropDownList2.SelectedItem.ToString & """"
Using con As New System.Data.SqlClient.SqlConnection(connexstring)
con.Open()
Using cmd As New SqlCommand(newsqlcommand, con)
Dim myReader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While myReader.Read()
DropDownList3.Items.Add(myReader.GetString(0))
End While
myReader.Close()
cmd.Dispose()
End Using
con.Close()
con.Dispose()
End Using
Dbind()
End Sub
This successfully reads all the items in the column "SWVersion" and adds them to the dropdown in dropdown3. Enjoy!

Passing value through path using postback url

I am using a datalist on customer page to list all customers. There is a page named "view" where I want to show the details of the particular selected customer. Here is the image button code:
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# GetImageURL(Eval("image")) %>' PostBackUrl='<%# Eval("id", "view.aspx?id={0}") %>'/></tr>
id is the unique field of the customer table. Now how should I retrieve the customer data on view.aspx, using the particular ID passed from the customer page. I use this code but it's not working:
Dim mycommand As New SqlCommand("SELECT * FROM customer where id = #id", con)
Int(ID = Request.QueryString("id"))
con.Open()
ProfileData.DataSource = mycommand.ExecuteReader
ProfileData.DataBind()
con.Close()
I just want to do that. In the customer page all customers are displayed with their image and when I click on any one of them then the details of the particular customer should be displayed on view.aspx page ..
you are using #id as CommandParameter to add this id as value to command parameter..
as
Dim mycommand As New SqlCommand("SELECT * FROM customer where id = #id", con)
mycommand.Parameters.Add("#id", SqlDbType.Int)
mycommand.Parameters("#id").Value = Convert.ToInt32( Request.QueryString("id"))
con.Open()
ProfileData.DataSource = mycommand.ExecuteReader
ProfileData.DataBind()
con.Close()
check these link to know about the parameter..
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
http://msdn.microsoft.com/en-us/library/yy6y35y8%28v=vs.80%29.aspx

Adding Column Value Dynamically to a DataGridview

I have three column in my datagridview .One is text ,one is Combo and another one is Text ...i don't want to use datasource want to add values on cell like datagridview.Rows[].cells[].value. Help me how i can do it? My database have several columns...How to add column value dynamically....
I just had to do the same exact type of thing...here is how you add a column.
If Not IsPostBack Then <br>
Dim field As New TemplateField
field.HeaderText = "Name of Column"
Dim col As DataControlField = field
GridView.Columns.Add(col)
End If
**In the Gridview_rowcreated Sub
e.row.cells(cellnumber from 0 to N).controls.Add(data)
you're going to have to create a connection and a connection string
here is an example...
Dim Dbconn As SqlConnection
Dim Dbcmd As SqlCommand
Dbcmd = New Data.SqlClient.SqlCommand()
Dbcmd.Connection = Dbconn
Dbcmd.CommandType = Data.CommandType.Text
Dbcmd.Commandtext = "select * from table"
dbconn.open()
//then you need a data reader
dim dr as sqlclient.sqldatareader
dr = dbcmd.executereader
while dr.read
add each item to a list
end while
then on page load set your datasource of the grid to the list
hope this helps...if you have any questions just ask me.
I would highly recommend to use a Repeater instead of datagridview and render as many columns as you want.
.aspx code
<tr>
<asp:Repeater ID="rptDayHeaders" runat="server">
<ItemTemplate>
<td>
<strong><asp:Literal ID="ltMonthHeader" runat="server"></asp:Literal></strong>
</td>
</ItemTemplate>
</asp:Repeater>
</tr>
.aspx.vb code
rptDayHeaders.DataSource = daysList
rptDayHeaders.DataBind()
where dayslist needs to be an array of the number of columns you want.
We have used the same approach to generate a complete Gantt Chart
Try something along the lines of
dataGrid.Rows.Add(new object[] { "value1", 42, "value3"});

Resources