How to assign a text field a database value

M

MasterChief

I am sending a page a query string called job_id. What I want to do is
take the job_id that is passed look it up in a database and make the
text in a label on the new page display a value of one of the fields.
Does anybody have any code for this? I just don't know how to databind
the text label to say a sql source or code and get the info. Thanks.
 
K

Ken Cox [Microsoft MVP]

Hi Master (a real name is nicer),

You need to decide what row and what column you want to appear in the label.
After that, you use DataBinder.Eval and the defaultview.

Here's an example in ASP.NET 2.0 that does it based on a datatable (built on
the fly).

Let us know if this helps?

Ken
Microsoft MVP [ASP.NET]


<%@ page language="VB" %>
<%@ import namespace="system.data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
' From Ken Cox Microsoft MVP [ASP.NET]
If Not IsPostBack Then
' Create a dataset
Dim ds As New DataSet
' Add a table to the dataset
ds.Tables.Add(CreateDataSource())
' Create a filter so that we only get one row
ds.Tables(0).DefaultView.RowFilter = "IntegerValue = 5"
' Pass the dataset and an expression to DataBinder.Eval
' so that it returns the string called StringValue in
' the default dataview
label1.Text = DataBinder.Eval(ds, _
"Tables(0).DefaultView(0).StringValue")
' Bind everything on the page
Page.DataBind()
End If
End Sub


Function CreateDataSource() As Data.DataTable
Dim dt As New Data.DataTable
Dim dr As Data.DataRow
dt.Columns.Add(New Data.DataColumn _
("IntegerValue", GetType(Int32)))
dt.Columns.Add(New Data.DataColumn _
("StringValue", GetType(String)))
dt.Columns.Add(New Data.DataColumn _
("CurrencyValue", GetType(Double)))
dt.Columns.Add(New Data.DataColumn _
("Boolean", GetType(Boolean)))
Dim i As Integer
For i = 0 To 5
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " + i.ToString()
dr(2) = 1.23 * (i + 1)
dr(3) = (i = 4)
dt.Rows.Add(dr)
Next i
Return dt
End Function
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind to a Label</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:label id="label1" runat="server">
</asp:label>
</div>
</form>
</body>
</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top