Multiple Outputs From One Set of Labels - sql

I am building a website in ASP.NET Web Forms with a SQL Database. The database contains a table with 571 entry's of data.
Output
Source Code
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("SELECT Id, Name, Townland, Near, Status, Built FROM Houses ORDER BY Name DESC", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
lblId.Text = reader[0].ToString();
lblName.Text = reader[1].ToString();
lblTown.Text = reader[2].ToString();
lblNear.Text = reader[3].ToString();
lblStatus.Text = reader[4].ToString();
lblBuilt.Text = reader[5].ToString();
}
}
}
}
Database
I want to display all 571 houses to do this I would need a set of labels for each house but is there a way I could have one set of labels like the above code to output all 571 entry's without repeating code.

Try to use a Repeater. This is a special control, which allows to define an inner item layout only once and then bind some data to render multiple blocks looking consistently, but containing the different data.
Repeater has ItemTempalte property, which allows you to wrap all the labels you want to see.
<asp:Repeater ID="rptData" runat="server">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
Then just load the DB rows into repeater:
rptData.DataSource = command.ExecuteReader();
rptData.DataBind();
And finally, in the HTML layout specify mapping for labels to respective columns - like
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
or
<asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
etc.

Related

How to Add an Empty, Unbound, Comment Column to a GridView?

I've put together a GridView table in ASP.net that allows users to approve a series of records. As part of this approval process, I'd like to provide an empty column for the user to provide comments where necessary. The only records showing up will be records that haven't been approved yet, thus, no comments will need to be loaded. Once they are approved, users will not be able to view these records again.
How do I go about adding this empty column to my GridView? Again, there's no data to load into this column. Once approved, the records in the SQL Server table will be updated with a timestamp and comments.
Most of what I was able to find on here so far has been related to adding empty rows, but not columns. I'm completely new to ASP.net, so any help would be greatly appreciated.
Current Column Code:
asp:TemplateField HeaderText="Comment" ItemStyle-Width="500px" ItemStyle-Wrap="true" SortExpression="Comment" /
Just a simple solution I've quickly put together. It uses the OnRowCommand event of the GridView.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="TextBox">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Text='<%# Eval("textfield") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UpdateButton">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Update" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//cast the sender back to a gridview
GridView gv = sender as GridView;
//cast the commandsource back to a button
Button btn = e.CommandSource as Button;
//cast the namingcontainer of the button back to a gridviewrow
GridViewRow row = btn.NamingContainer as GridViewRow;
//find the correct textbox using findcontrol and the index obtained from the row
TextBox tb = gv.Rows[row.DataItemIndex].FindControl("TextBox1") as TextBox;
//show result
Label1.Text = tb.Text;
}
UPDATE
Or if you want to update all the records at once by pressing a button.
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
TextBox tb = row.FindControl("TextBox1") as TextBox;
Label1.Text += tb.Text + "<br>";
}
}

Gridview Calculated Field in Row

I am using Visual Studio 2010 and Visual Basic linked to a SQL database. I have a Gridview in which I want to have a calculated field, let's call it NoHoursOff, based on the fields in that row - BeginTimeOff and EndTimeOff.
After doing some research, I learned that I should use a TemplateField. I just don't understand how this works. I have tried with no success:
<asp:TemplateField HeaderText="Total Hours" >
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# "EndTimeOff" - "BeginTimeOff" %>' Width="100px"></asp:Label>>
</ItemTemplate>
</asp:TemplateField>
I also have tried replacing Text value with "EndTimeOff".subtract("BeginTimeOff") which works on another webpage. I don't understand how to do a calculated field! Please help or can you direct me to a tutorial that would explain this to me.
You need to create a function in the codebehind like this
public string getValue(object BeginTimeOff, object EndTimeOff)
{
return (Convert.ToDateTime(EndTimeOff.ToString()) - Convert.ToDateTime(BeginTimeOff.ToString())).ToString();
}
and in the Label this
Text=<%# getValue(Eval("BeginTimeOff"), Eval("EndTimeOff")) %>
then just set the format you want to display in the method (n days, hh.mm.ss, etc) to fit your requirement
Per your suggestions, I can't get it to work. Here is my aspx and vb code:
<asp:TemplateField HeaderText="TotalHours2" >
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# getValue(Eval("BeginTimeOff"), Eval("EndTimeOff")) %>' Width="100px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
AND
Public Function getValue(BeginTimeOff As Object, EndTimeOff As Object) As String
Return (DateTime.Parse(EndTimeOff.ToString()) - DateTime.Parse(BeginTimeOff.ToString())).ToString()
End Function
It's probably something wrong with my attempt to convert C# to VB. Thanks for all your help! (FYI - I did get another function to work using your example - just not this new function. If you want to see code, I'll show it to you. It counts days between 2 dates, not including weekends and holidays. Thanks a million for helping me figure that one out!)

ASP.Net DropDownList Retains Value From Database - AutoPostBack

I have been stuck in this problem for along time, searched online but no solution yet solved my problem. I have a dropdownlist where it retrieved the plan names from a table in my databse based on the zip code that is entered in a text field. The problem I am running into is: when I enter a zip code, the plan names populate with no problem in the dropdownlist, then I select one of the plans, when I go further and try to enter other info in other fields which have autppostback = true, the dropdownlist does not retain its value and always select the first value, I want the dropdownlist to retain the selected value after the postback, here is my code:
step1.aspx
<p>
<asp:TextBox ID="txt_zip_code" runat="server" AutoPostBack="true"></asp:TextBox>
</p>
<p>
<asp:DropDownList ID="dd_dental_plan" runat="server" EnableViewState="true">
</asp:DropDownList>
</p>
step1.cs
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.CommandText = "SELECT * FROM [dbo].[mfd_plans] WHERE zip_code = #zipCode";
sqlCmd.Parameters.AddWithValue("#zipCode", txt_zip_code.Text);
sqlCmd.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
DataTable dt = new DataTable();
da.Fill(dt);
dd_dental_plan.DataSource = dt;
dd_dental_plan.DataValueField = "plan_id";
dd_dental_plan.DataTextField = "plan_name";
dd_dental_plan.DataBind();
conn.Close();
dd_dental_plan.Items.Insert(0, new ListItem("Please select plan", "0"));
}
}
you should use update panel on your aspx page for preventing whole page load when autopostback occurs from another fields.
just put an asp:scriptmanager control on your page. After the put your zip code and dropdownlist into update panel and put other controls in separate update panels by which post back occurs. your code will look like this.
<asp:ScriptManager runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<p>
<asp:TextBox ID="txt_zip_code" runat="server" AutoPostBack="true"></asp:TextBox>
</p>
<p>
<asp:DropDownList ID="dd_dental_plan" runat="server" EnableViewState="true">
</asp:DropDownList>
</p>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
another controls which caused postback event
</ContentTemplate>
</asp:UpdatePanel>
another controls which don't cause postback.
</div>
Hope this will works.enter code here
Thanks
Umm I really hoped that I understand your Question correctly ..
Have you tried something like
if (!Page.IsPostBack)
{// All the code that you've written above ..}
and do that with all you're codes that you write in Page_Load ...
give it a try ...

visual studio 2010 Getting value from gridview

How do I get the value in a gridview when one hits the "Select" link in a row?
If I have a databound, I can get that value. However I am trying to highlight certain labels.The "HighlightTex" function lets me highlight some words that the user selects.
Here is a snippet: I am trying to get the value of "lblinvnum".
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1" Width="540px"
CssClass="Gridview" >
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:TemplateField HeaderText="Invnum" ItemStyle-Wrap="False">
<ItemTemplate>
<asp:Label ID="lblInvnum" Text='<%# HighlightText(Eval("Invnum").ToString()) %>' runat="server" />
</ItemTemplate>
...
...
... For the "AmtPaid" listed below, I can Get that value. I cannot figure out how to get the value for "lblInvnum" to the snippet listed above.
<asp:BoundField DataField="AmtPaid" HeaderText="AmtPaid"
SortExpression="AmtPaid" DataFormatString="{0:c}" >
In visual basic, this is how I can get the one above for AmtPaid.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim selectedRow As GridViewRow = gvDetails.Rows(index)
Dim contactCell As TableCell = selectedRow.Cells(1)
Dim contact As String = contactCell.Text
Suggestions?

how to retrieve binary image from database in vb.net and insert the image in grid view

How to retrieve a binary image from a database using vb.net and insert the image into a GridView.
This is my DB
image (id as integer , img as varbinary(max))
While you clarify the type of gridview you are referring to, here's how to insert the data in the database:
Using c As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
c.Open()
Dim command = New SqlCommand("INSERT INTO yourtable(image) values (#image)", c)
' this is specific to the FileUploadControl but the idea is to get the
'image in a byte array; however you do it, it doesn't matter
Dim buffer(FileUpload1.PostedFile.ContentLength) As Byte
FileUpload1.PostedFile.InputStream.Read(buffer, 0, buffer.Length)
command.Parameters.AddWithValue("#image", buffer)
command.ExecuteNonQuery()
End Using
And assuming you are talking about an ASP .NET app, you can bind the data to the gridview as follows:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<!--Trick to encode the bytes as a BASE64 string-->
<img width="100px" height="100px" src='data:image/png;base64,<%#System.Convert.ToBase64String(Eval("image"))%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=Your_ConnectionString_GoesHere"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [id], [image] FROM [your_table_name_goes_here]">
</asp:SqlDataSource>