In a DetailsView I have set visible = false for a TemplateField with HeaderText of "No Treatment Reason:".
In the code behind how can I reference the DataRow explicitly and make it visible based on the value of the other TemplateField with the HeaderText of "Care Plan Intent:" ?
<asp:DetailsView ID="dvTest" FooterStyle-Width="100%" Font-Bold="false" BackColor="#A2C4EA"
FieldHeaderStyle-Width="35%" BorderWidth="1" CellSpacing="2" Font-Names="Arial, Helvetica, sans-serif"
Font-Size="12px" runat="server" AutoGenerateRows="False" AllowPaging="False" style="width:98%"
HeaderStyle-BackColor="White" HeaderStyle-Font-Bold="true" HeaderStyle-HorizontalAlign="center">
<Fields>
<asp:TemplateField HeaderText="Care Plan Intent:">
<ItemTemplate>
<asp:Label skinid="tablabelblack" id="lblIntent" runat="server" Text='<%# Eval("CarePlanIntent") %>' />
<asp:HiddenField runat="server" ID="hidCarePlanIntent" Value='<%# Eval("CarePlanIntent") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="No Treatment Reason:" Visible="false">
<ItemTemplate>
<asp:Label skinid="tablabelblack" id="lblNoTreatmentReason" runat="server" Text='<%# Eval("NoTreatmentReason") %>' />
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
You have to use the DataBound event and cast the DataItem to the correct type (f.e. DataRowView). You can use FindControl to get your controls and following LINQ query to get the correct column to make it (in)visible:
protected void dvTest_DataBound(Object sender, EventArgs e)
{
var noTreatCol = this.dvTest.Fields.Cast<DataControlField>()
.First(field => field.HeaderText == "No Treatment Reason:");
DataRow row = ((DataRowView) dvTest.DataItem).Row;
Label tablabelblack = (Label)dvTest.FindControl("tablabelblack");
HiddenField hidCarePlanIntent = (HiddenField)dvTest.FindControl("hidCarePlanIntent");
string value = row.Field<string>("Value"); // just an example
noTreatCol.Visible = value == "SomeValueThatMakesItVisible";
}
Is it possible to do that in VB and without LINQ?
Of course:
Protected Sub dvTest_DataBound(sender As Object, e As EventArgs)
Dim row As DataRow = DirectCast(dvTest.DataItem, DataRowView).Row
Dim tablabelblack As Label = DirectCast(dvTest.FindControl("tablabelblack"), Label)
Dim hidCarePlanIntent As HiddenField = DirectCast(dvTest.FindControl("hidCarePlanIntent"), HiddenField)
Dim value As String = row.Field(Of String)("Value") ' just an example '
Dim noTreatColIndex As Int32 = -1
For i As Int32 = 0 To Me.dvTest.Fields.Count - 1
Dim field = dvTest.Fields(i)
If field.HeaderText = "No Treatment Reason:" Then
noTreatColIndex = i
Exit For
End If
Next
If noTreatColIndex > -1 Then
dvTest.Fields(noTreatColIndex).Visible = value = "SomeValueThatMakesItVisible"
End If
End Sub
I am working on an aspx site that lets an admin-level user fill out a form with potential member data. Once the form is filled out, the user will click submit and the data will go off to different tables. One part of the form that is stumping me involves filling out three textboxes (txtFirstName, txtLastName, txtGrade). I have a button (btnAddStudent), that, when clicked, should add the information from the textboxes to a table-like display area. I am trying to use a gridview, but there is nothing to bind it to. There is no memberID number to load a blank record from the Student table (which is a many-to-one relation to Member table). The member record is what this form is creating, and the student data will be added to the Student table when the Submit button is clicked.
I am currently working with the code found in the reply here. But when I click the "Add Student" button, I get a new blank row, but my textbox values are not inputted in the gridview.
Can this work, or do I need to look at using a table and adding rows of textboxes dynamically?
Here is relevant source code:
<tr>
<td class="style8">
<asp:Label ID="Label18" runat="server" Text="Chidren:" Font-Bold="True" Font- Underline="True" Font-Names="Tahoma"></asp:Label>
</td>
</tr>
<tr>
<td class="style8">
<asp:Label ID="Label19" runat="server" Text="First Name:"></asp:Label>
</td>
<td class="style7">
<asp:TextBox ID="txtChildFirstName" runat="server" CssClass="textbox"></asp:TextBox>
</td>
<td class="">
<asp:Label ID="Label20" runat="server" Text="Last Name:"></asp:Label>
</td>
<td class="style6">
<asp:TextBox ID="txtChildLastName" runat="server" CssClass="textbox"></asp:TextBox>
</td>
<td class="style5" align="right">
<asp:Label ID="Label21" runat="server" Text="Grade:"></asp:Label>
</td>
<td class="style4">
<asp:TextBox ID="txtGrade" runat="server" Width="52px" CssClass="textbox"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnAddChild" runat="server" Text="Add Child" OnClick="btnAddChild_Click" />
</td>
</tr>
<tr>
<td valign="top" class="style8">
<asp:Label ID="Label22" runat="server" Text="Student List:"></asp:Label>
</td>
<td colspan="3">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="gvStudentList" runat="server" AutoGenerateColumns="False"
PageSize="5" Height="42px">
<AlternatingRowStyle BackColor="#E0E0E0" />
<Columns>
<asp:BoundField AccessibleHeaderText="FirstName" HeaderText="First Name" />
<asp:BoundField AccessibleHeaderText="LastName" HeaderText="Last Name" />
<asp:BoundField AccessibleHeaderText="Grade" HeaderText="Grade" />
</Columns>
<HeaderStyle BackColor="#CCCCCC" Height="25px" />
<RowStyle Height="22px" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
And the Code Behind:
'A method that will BIND the GridView based on the TextBox
'values and retain its values on post backs.
Private Sub BindGrid(rowcount As Integer)
Dim dt As New DataTable()
Dim dr As DataRow
dt.Columns.Add(New System.Data.DataColumn("FirstName", GetType([String])))
dt.Columns.Add(New System.Data.DataColumn("LastName", GetType([String])))
dt.Columns.Add(New System.Data.DataColumn("Grade", GetType([String])))
If ViewState("CurrentData") IsNot Nothing Then
For i As Integer = 0 To rowcount
dt = DirectCast(ViewState("CurrentData"), DataTable)
If dt.Rows.Count > 0 Then
dr = dt.NewRow()
dr(0) = dt.Rows(0)(0).ToString()
End If
Next
dr = dt.NewRow()
dr(0) = txtChildFirstName.Text
dr(1) = txtChildLastName.Text
dr(2) = txtGrade.Text
dt.Rows.Add(dr)
Else
dr = dt.NewRow()
dr(0) = txtChildFirstName.Text
dr(1) = txtChildLastName.Text
dr(2) = txtGrade.Text
dt.Rows.Add(dr)
End If
' If ViewState has a data then use the value as the DataSource
If ViewState("CurrentData") IsNot Nothing Then
gvStudentList.DataSource = DirectCast(ViewState("CurrentData"), DataTable)
gvStudentList.DataBind()
Else
' Bind GridView with the initial data assocaited in the DataTable
gvStudentList.DataSource = dt
gvStudentList.DataBind()
End If
' Store the DataTable in ViewState to retain the values
ViewState("CurrentData") = dt
End Sub
Protected Sub btnAddChild_Click(sender As Object, e As EventArgs) Handles btnAddChild.Click
' Check if the ViewState has a data assoiciated within it. If
If ViewState("CurrentData") IsNot Nothing Then
Dim dt As DataTable = DirectCast(ViewState("CurrentData"), DataTable)
Dim count As Integer = dt.Rows.Count
BindGrid(count)
Else
BindGrid(1)
End If
txtChildFirstName.Text = String.Empty
txtChildLastName.Text = String.Empty
txtGrade.Text = String.Empty
txtChildFirstName.Focus()
End Sub
With "BindGrid()" being called in the Page_Load event. (And yes, I have ScriptManager)
Try to use
Session("CurrentData") = dt on your BindGrid()
Then Create Method that just refreshes the grid after postback:
Private Sub RefreshGrid()
{
If ViewState("CurrentData") IsNot Nothing Then
gvStudentList.DataSource = DirectCast(Session("CurrentData"), DataTable)
gvStudentList.DataBind()
Else
gvStudentList.DataSource = null;
gvStudentList.DataBind()
EndIf
}
On your page load just call:
If IsPostBack Then
Return
End If
RefreshGrid()
Regards
I'm a little stuck on what to do! I have a special form that allows my customers to request a quote for a specific product (defined by PID in url) The form is loaded inside a modal dialogue and within that a Iframe. The Iframe's src value is set from the onclick event of ahref on the product pages eg;
<div id='basic-modal'><p><br /><br />CLICK ME</p></div>
<div id="basic-modal-content">
<iframe id="ifr" width="850px" height="600px" frameborder="0" scrolling="no"></iframe>
The form that I am loading does a SQL insert when Page_Load is fired. Also it is within
If Page.IsPostBack = False Then
For some strange reason the page is doing it twice when the page loads and another time when the page is closed.. I need the SQL insert on the first page load as the returned values are used by my form. Can anyone suggest a good way of making the code within Page_Load only fire up once?
Many thanks!
UPDATE, Full Code:
aspx page
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Public_Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="../quoteFront.css" rel="stylesheet" type="text/css" />
<title></title>
<style type="text/css">
.style1
{
width: 100%;
}
.style2
{
height: 26px;
}
.style5
{
width: 299px;
}
.style6
{
width: 174px;
}
.style7
{
height: 26px;
width: 174px;
}
.style8
{
width: 291px;
}
.style9
{
height: 26px;
width: 189px;
}
.style10
{
}
.style11
{
width: 189px;
}
.style12
{
width: 191px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePartialRendering="true" CombineScripts="false" >
</cc1:ToolkitScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel3" runat="server"><ContentTemplate>
<asp:Panel ID="Panel2" runat="server">
<table class="style1">
<tr>
<td class="style12">
First name</td>
<td class="style5">
<asp:TextBox ID="txtFirstName" runat="server" Width="300px"
AutoCompleteType="FirstName"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtFirstName" ErrorMessage="* Required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style12">
Last name</td>
<td class="style5">
<asp:TextBox ID="txtLastName" runat="server" Width="300px"
AutoCompleteType="LastName"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtLastName" ErrorMessage="* Required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style12">
Company name</td>
<td class="style5">
<asp:TextBox ID="txtCompanyName" runat="server" Width="300px"
AutoCompleteType="Company"></asp:TextBox>
</td>
<td>
</td>
</tr>
<tr>
<td class="style12">
Email address</td>
<td class="style5">
<asp:TextBox ID="txtEmailAddress" runat="server" Width="300px" AutoCompleteType="Email"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="txtEmailAddress" ErrorMessage="* Required"
ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="txtEmailAddress" ErrorMessage=" * Invalid email address"
ForeColor="Red"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style12">
Phone number</td>
<td class="style5">
<asp:TextBox ID="txtPhoneNumber" runat="server" Width="300px" AutoCompleteType="BusinessPhone"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ControlToValidate="txtPhoneNumber" ErrorMessage="* Required"
ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div>
<table class="style1">
<tr>
<td class="style11">
Quantity required</td>
<td class="style6">
<asp:TextBox ID="txtQuantity1" runat="server" AutoPostBack="True"></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="ftbe" runat="server" FilterType="Numbers"
TargetControlID="txtQuantity1" />
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
ControlToValidate="txtQuantity1"
ErrorMessage="* Please enter quantity required" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style11">
<asp:Label ID="lblDesigninfo" runat="server" Text="Printing info"></asp:Label>
</td>
<td class="style6">
<asp:DropDownList ID="drpDesignInfo1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="PrintInfoDesc"
DataValueField="ID" AppendDataBoundItems="True">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:quotingSystemConnectionString %>"
SelectCommand="SELECT [ID], [PrintInfoDesc] FROM [PrintInfo]">
</asp:SqlDataSource>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ControlToValidate="drpDesignInfo1" ErrorMessage="* Please select"
ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style11">
<asp:Label ID="lblColoursSideOne1" runat="server"
Text="Colour options first side" Visible="True"></asp:Label>
</td>
<td class="style6">
<asp:DropDownList ID="drpColoursSideOne1" runat="server" Visible="True"
AutoPostBack="True">
</asp:DropDownList>
</td>
<td>
</td>
</tr>
<tr>
<td class="style9">
<asp:Label ID="lblColoursSideTwo1" runat="server"
Text="Colour options second side" Visible="false"></asp:Label>
</td>
<td class="style7">
<asp:DropDownList ID="drpColoursSideTwo1" runat="server" Visible="false">
</asp:DropDownList>
</td>
<td class="style2">
</td>
</tr>
</table>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtQuantity1" EventName="TextChanged" />
<asp:AsyncPostBackTrigger ControlID="drpDesignInfo1"
EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="drpColoursSideOne1"
EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate>
<div style="text-align: center">Please fill in the above fields before uploading
artwork.
<br />
When the upload is complete you will get the option to upload additional
artwork.
<cc1:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
CompleteBackColor="Lime" ErrorBackColor="Red"
OnClientUploadComplete="UploadComplete" OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete" ThrobberID="Throbber"
UploaderStyle="Modern" UploadingBackColor="#66CCFF" Width="100%"
ClientIDMode="Inherit" />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="../Images/indicator.gif" align="absmiddle" alt="loading" />
</asp:Label><asp:Label ID="lblStatus" runat="server"></asp:Label>
<br />
<div style="max-height:70px; overflow : auto; ">
<asp:Label ID="lblUploadList" runat="server" ForeColor="#006600"
Font-Size="Smaller"></asp:Label>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<table class="style1">
<tr>
<td class="style10">
Any aditional info<asp:TextBox ID="txtComments" runat="server" Height="111px"
TextMode="MultiLine" Width="100%"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style8">
<asp:Button ID="Button1" runat="server" Text="Send Request" Width="100%"
Height="45px" Font-Bold="False" />
</td>
</tr>
</table>
</asp:Panel>
<br />
<asp:Panel ID="Panel1" runat="server" Visible="False">
Thank you for requesting a quote. A member of our sales team will be in touch
shortly.<br />
<br />
<asp:Button ID="btnRequestAnother" runat="server"
Text="Request another quote for this product" CausesValidation="False"
Height="45px" Width="100%"/>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript" language="javascript">
function uploadError(sender, args) {
document.getElementById("lblStatus").innerHTML = "Failed to upload " + args.get_fileName() + ". Please try again. If problem persistes please email sales#thecleverbaggers.co.uk";
document.getElementById("Button1").innerHTML = 'Send Request';
}
function StartUpload(sender, args) {
document.getElementById("lblStatus").innerHTML = 'Uploading Started. Depending on your connection speed this can take a very long time. Please wait....';
document.getElementById("Button1").innerHTML = 'Uploading Started. Please Wait....';
}
function UploadComplete(sender, args) {
var filename = args.get_fileName();
var contentType = args.get_contentType();
var text = "Upload Complete, Press Select File to upload more. " //"Size of " + filename + " is " + args.get_length() + " bytes";
if (contentType.length > 0) {
text //+= " and content type is '" + contentType + "'.";
}
document.getElementById("lblStatus").innerHTML = text;
document.getElementById("lblUploadList").innerHTML = document.getElementById("lblUploadList").innerHTML + "<br />" + filename + " Uploaded Successfully";
document.getElementById("Button1").innerHTML = 'Send Request';
}
</script>
</form>
</body>
VB CODE:
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Partial Class Public_Default
Inherits System.Web.UI.Page
Dim ArtworkID As Integer
Dim customerIDDecrypt As String
Public QuoteID As Integer
Dim UploadedFileList As String
Dim productID As String
'Shared IsFirstTime As Boolean = False
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
productID = Request.QueryString("PID")
customerIDDecrypt = "0"
'If Not Page.IsPostBack AndAlso Not IsFirstTime Then
If Not Page.IsPostBack Then
Try
Dim sql As String = "INSERT INTO [Quote] (Status, CreationDate, CreationTime, CustomerID, ProductID, IP)" & _
"VALUES (#Status, #CreationDate, #CreationTime, #CustomerID, #ProductID, #IP) SELECT SCOPE_IDENTITY()"
Using cn As New SqlConnection(ConfigurationManager.AppSettings("quotingSystemConnectionString")), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#Status", SqlDbType.NVarChar).Value = 1
cmd.Parameters.Add("#CreationDate", SqlDbType.Date).Value = Date.UtcNow.ToLocalTime
cmd.Parameters.Add("#CreationTime", SqlDbType.Time).Value = Date.UtcNow.ToLocalTime.TimeOfDay
cmd.Parameters.Add("#CustomerID", SqlDbType.Int).Value = customerIDDecrypt
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = productID
cmd.Parameters.Add("#IP", SqlDbType.NVarChar).Value = CStr(Request.UserHostAddress())
cn.Open()
'//grab the ID of this insert.
QuoteID = Integer.Parse(cmd.ExecuteScalar().ToString())
cn.Close()
'IsFirstTime = True
End Using
Catch ex As Exception
'// do something with this error!
Response.Write(ex.Message)
End Try
End If
End Sub
Protected Sub txtQuantity1_TextChanged(sender As Object, e As System.EventArgs) Handles txtQuantity1.TextChanged
'//populate colours dependant on quantity
If txtQuantity1.Text > "" Then
If txtQuantity1.Text < "100" Then
'side one
drpColoursSideOne1.Items.Clear()
'drpColoursSideOne1.Enabled = True
drpColoursSideOne1.Items.Add(New ListItem("One colour", "1"))
drpColoursSideOne1.Items.Add(New ListItem("More than one colour", "full"))
drpColoursSideOne1.Items.Add(New ListItem("I don't know!", "help"))
drpColoursSideOne1.Visible = True
'side two
drpColoursSideTwo1.Items.Clear()
'drpColoursSideTwo1.Enabled = True
drpColoursSideTwo1.Items.Add(New ListItem("One colour", "1"))
drpColoursSideTwo1.Items.Add(New ListItem("More than one colour", "full"))
drpColoursSideTwo1.Items.Add(New ListItem("I don't know!", "help"))
drpColoursSideTwo1.Items.Add(New ListItem("na", "na"))
Else
'side one
drpColoursSideOne1.Items.Clear()
'drpColoursSideOne1.Enabled = True
drpColoursSideOne1.Items.Add(New ListItem("One colour", "1"))
drpColoursSideOne1.Items.Add(New ListItem("Two colours", "2"))
drpColoursSideOne1.Items.Add(New ListItem("Three colours", "3"))
drpColoursSideOne1.Items.Add(New ListItem("Four colours", "4"))
drpColoursSideOne1.Items.Add(New ListItem("Five colours", "5"))
drpColoursSideOne1.Items.Add(New ListItem("Full colour (eg, photo)", "full"))
drpColoursSideOne1.Items.Add(New ListItem("I don't know!", "help"))
'side two
drpColoursSideTwo1.Items.Clear()
'drpColoursSideTwo1.Enabled = True
drpColoursSideTwo1.Items.Add(New ListItem("One colour", "1"))
drpColoursSideTwo1.Items.Add(New ListItem("Two colours", "2"))
drpColoursSideTwo1.Items.Add(New ListItem("Three colours", "3"))
drpColoursSideTwo1.Items.Add(New ListItem("Four colours", "4"))
drpColoursSideTwo1.Items.Add(New ListItem("Five colours", "5"))
drpColoursSideTwo1.Items.Add(New ListItem("Full colour (eg, photo)", "full"))
drpColoursSideTwo1.Items.Add(New ListItem("I don't know!", "help"))
drpColoursSideTwo1.Items.Add(New ListItem("na", "na"))
End If
Else
'nothing
End If
End Sub
Protected Sub drpDesignInfo1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpDesignInfo1.SelectedIndexChanged
If drpDesignInfo1.SelectedValue = "1" And txtQuantity1.Text > "0" Then
lblColoursSideTwo1.Visible = False
lblColoursSideOne1.Visible = True
drpColoursSideOne1.Visible = True
drpColoursSideOne1.Enabled = True
drpColoursSideTwo1.Visible = False
drpColoursSideTwo1.Enabled = False
drpColoursSideTwo1.SelectedValue = "na"
' drpColoursSideTwo1.Items.Remove(New ListItem("Same as the first side", "same"))
ElseIf drpDesignInfo1.SelectedValue = "3" And txtQuantity1.Text > "0" Then
lblColoursSideOne1.Visible = True
drpColoursSideOne1.Visible = True
drpColoursSideOne1.Enabled = True
lblColoursSideTwo1.Visible = True
drpColoursSideTwo1.Visible = True
drpColoursSideTwo1.Enabled = True
' drpColoursSideTwo1.Items.Remove(New ListItem("Same as the first side", "same"))
ElseIf drpDesignInfo1.SelectedValue = "2" And txtQuantity1.Text > "0" Then
lblColoursSideOne1.Visible = True
drpColoursSideOne1.Visible = True
drpColoursSideOne1.Enabled = True
lblColoursSideTwo1.Visible = True
drpColoursSideTwo1.Visible = True
drpColoursSideTwo1.Enabled = False
' Dim tmpCount2 = drpColoursSideTwo1.Items.Count
' If tmpCount2 = 7 Or tmpCount2 = 3 Then
'drpColoursSideTwo1.Items.Add(New ListItem("Same as the first side", "same"))
'End If
drpColoursSideTwo1.SelectedValue = drpColoursSideOne1.SelectedValue
End If
End Sub
Protected Sub AsyncFileUpload1_UploadedComplete(sender As Object, e As AjaxControlToolkit.AsyncFileUploadEventArgs)
System.Threading.Thread.Sleep(3000)
If AsyncFileUpload1.HasFile Then
'Dim strPath As String = newPath + Path.GetFileName(e.FileName)
'AsyncFileUpload1.SaveAs(strPath)
Dim fileName = Path.GetFileName(e.FileName)
'Dim imageBytes(AsyncFileUpload1.PostedFile.InputStream.Length) As Byte
'AsyncFileUpload1.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.length)
Dim imageBytes = AsyncFileUpload1.FileBytes
'AsyncFileUpload1.FileBytes
'// now insert this into the database
Try
Dim sql As String = "INSERT INTO [UploadedFiles] (CustomerID, FileName, FileSize, FileContent, FileType, FileUploadDate, QuoteID)" & _
"VALUES (#CustomerID, #FileName, #FileSize, #FileContent, #FileType, #FileUploadDate, #QuoteID) SELECT SCOPE_IDENTITY()"
Using cn As New SqlConnection(ConfigurationManager.AppSettings("quotingSystemConnectionStringLargeTimeout")), _
cmd As New SqlCommand(sql, cn)
cmd.CommandTimeout = "3600"
cmd.Parameters.Add("#CustomerID", SqlDbType.Int).Value = 1
cmd.Parameters.Add("#FileName", SqlDbType.NVarChar).Value = fileName
cmd.Parameters.Add("#FileSize", SqlDbType.NVarChar).Value = AsyncFileUpload1.PostedFile.ContentLength
cmd.Parameters.Add("#FileContent", SqlDbType.VarBinary).Value = imageBytes
cmd.Parameters.Add("#FileType", SqlDbType.NVarChar, 50).Value = AsyncFileUpload1.PostedFile.ContentType
cmd.Parameters.Add("#FileUploadDate", SqlDbType.Date).Value = Date.UtcNow.ToLocalTime
cmd.Parameters.Add("#QuoteID", SqlDbType.Int).Value = QuoteID
cn.Open()
'//grab the ID of this insert.
ArtworkID = Integer.Parse(cmd.ExecuteScalar().ToString())
cn.Close()
End Using
Catch ex As Exception
'// do something with this error!
Response.Write(ex.Message)
End Try
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
'// Populate the database with remaining information
Button1.Text = "Please Wait... Sending Request"
Dim thisConnection As New SqlConnection(ConfigurationManager.AppSettings("quotingSystemConnectionString"))
'Create Command object
Dim nonqueryCommand As SqlCommand = thisConnection.CreateCommand()
Try
' Open Connection
thisConnection.Open()
' 1. Create Command
' Sql Update Statement
Dim updateSql As String = "UPDATE Quote " & _
"SET Status = '2', FirstName = #FirstName, LastName = #LastName, CompanyName = #CompanyName, Email = #Email, Phone = #Phone, Quantity = #Quantity, DesignInfo = #DesignInfo, CS1 = #CS1, CS2 = #CS2, Comments = #Comments " & _
"WHERE QuoteID = " & QuoteID
Dim UpdateCmd As New SqlCommand(updateSql, thisConnection)
' 2. Map Parameters
'UpdateCmd.Parameters.Add("#Status", SqlDbType.Int, "Status")
UpdateCmd.Parameters.Add("#FirstName", SqlDbType.NVarChar, 100, "FirstName")
UpdateCmd.Parameters.Add("#LastName", SqlDbType.NVarChar, 100, "LastName")
UpdateCmd.Parameters.Add("#CompanyName", SqlDbType.NVarChar, 100, "CompanyName")
UpdateCmd.Parameters.Add("#Email", SqlDbType.NVarChar, 200, "Email")
UpdateCmd.Parameters.Add("#Phone", SqlDbType.NVarChar, 30, "Phone")
UpdateCmd.Parameters.Add("#Quantity", SqlDbType.Int, 20, "Quantity")
UpdateCmd.Parameters.Add("#DesignInfo", SqlDbType.NVarChar, 100, "DesignInfo")
UpdateCmd.Parameters.Add("#CS1", SqlDbType.NVarChar, 20, "CS1")
UpdateCmd.Parameters.Add("#CS2", SqlDbType.NVarChar, 20, "CS2")
UpdateCmd.Parameters.Add("#Comments", SqlDbType.NVarChar, 1000, "Comments")
''''''''''''''
'UpdateCmd.Parameters("#Status").Value = 2
UpdateCmd.Parameters("#FirstName").Value = txtFirstName.Text
UpdateCmd.Parameters("#LastName").Value = txtLastName.Text
UpdateCmd.Parameters("#CompanyName").Value = txtCompanyName.Text
UpdateCmd.Parameters("#Email").Value = txtEmailAddress.Text
UpdateCmd.Parameters("#Phone").Value = txtPhoneNumber.Text
UpdateCmd.Parameters("#Quantity").Value = txtQuantity1.Text
UpdateCmd.Parameters("#DesignInfo").Value = drpDesignInfo1.SelectedValue
UpdateCmd.Parameters("#CS1").Value = drpColoursSideOne1.SelectedValue
Dim CS2 As String
If drpDesignInfo1.SelectedValue = "1" Then
CS2 = "na"
Else
CS2 = drpColoursSideTwo1.SelectedValue
End If
UpdateCmd.Parameters("#CS2").Value = CS2
UpdateCmd.Parameters("#Comments").Value = txtComments.Text
'QuoteID
'''''''''''''''
UpdateCmd.ExecuteNonQuery()
Catch ex As SqlException
' Display error
Response.Write("FAIL: " & ex.Message)
Finally
' Close Connection
thisConnection.Close()
Panel1.Visible = True
Panel2.Visible = False
End Try
End Sub
Protected Sub btnRequestAnother_Click(sender As Object, e As System.EventArgs) Handles btnRequestAnother.Click
QuoteID = Nothing
Response.Redirect(Request.RawUrl)
Panel1.Visible = False
Panel2.Visible = True
'IsFirstTime = False
End Sub
Protected Sub drpColoursSideOne1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpColoursSideOne1.SelectedIndexChanged
If drpDesignInfo1.SelectedValue = "2" Then
drpColoursSideTwo1.SelectedValue = drpColoursSideOne1.SelectedValue
End If
End Sub
End Class
Please excuse my messy code...
you can do like this:
static bool IsFirstTime = false;
After this
if(!Page.IsPostBack && !IsFirstTime)
{
insertdata();
IsFirstTime = true;
}
insertdata() inserts data into database.
I have a pretty simple scenario using manual data operations with rad list view. I insert an item into my collection in the ItemInserting event, the listview shows the new item but the insertitemtemplate is still showing. Is my setup wrong? Do I have to manually hide the thing?
Markup
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Test2.aspx.vb" Inherits="Test2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<telerik:RadScriptManager runat="server" ID="rsm"></telerik:RadScriptManager>
<div>
<telerik:RadListView ID="rlv" runat="server" DataKeyNames="UserID" ItemPlaceholderID="itemPlaceholder" Height="400px" AllowPaging="true">
<InsertItemTemplate>
<tr>
<td>
<div style="vertical-align: middle; white-space: nowrap;">
<asp:LinkButton ID="btnInsert2" runat="server" Text="Insert" CommandName='<%# Telerik.Web.UI.RadListView.PerformInsertCommandName %>'></asp:LinkButton>
<asp:LinkButton ID="btnCancel2" runat="server" Text="Cancel" CommandName='<%# Telerik.Web.UI.RadListView.CancelCommandName %>'></asp:LinkButton>
</div>
</td>
<td>
<div style="vertical-align: middle; white-space: nowrap;">
<telerik:RadComboBox id="RadComboBox1" runat="server" autopostback="True" causesvalidation="False" allowcustomtext="True" backcolor="White" emptymessage="Select a Person" enableloadondemand="True" showmoreresultsbox="True" width="150px" dropdownwidth="200px" zindex="9002" enablescreenboundarydetection="False" style="margin-bottom: 0px" datatextfield="UserName" datavaluefield="pkUserID" filter="Contains" onitemsrequested="RCB_ItemsRequested">
<CollapseAnimation Duration="200" Type="OutQuint" />
</telerik:RadComboBox>
</div>
</td>
</tr>
</InsertItemTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Literal ID="lName" runat="server" Text='<%# Eval("UserName") %>'></asp:Literal>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<asp:LinkButton ID="btnInsert" runat="server" CausesValidation="False" CommandName='<%# Telerik.Web.UI.RadListView.InitInsertCommandName %>' Text="Add User" />
<table>
<tr>
<td style="border: ridge 1px lightgray">
<strong>Applicable Users</strong>
<table>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</telerik:RadListView>
</div>
</form>
</body>
</html>
Code Behind
Partial Class Test2
Inherits System.Web.UI.Page
Public Property Users As IList(Of UserInfo)
Get
Return If(ViewState("Users"), New List(Of UserInfo))
End Get
Set(ByVal value As IList(Of UserInfo))
ViewState("Users") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Me.Users = GetInitialUsers()
End If
rlv.DataSource = Users
rlv.DataBind()
Me.ViewState.SetItemDirty("Users", True)
End Sub
Private Function GetInitialUsers() As IList(Of UserInfo)
Dim Users As New List(Of UserInfo)
Users.Add(New UserInfo(1, "1"))
Users.Add(New UserInfo(2, "2"))
Users.Add(New UserInfo(3, "2"))
Users.Add(New UserInfo(4, "4"))
Return Users
End Function
Protected Sub RCB_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs)
Dim ComboBox As Telerik.Web.UI.RadComboBox = sender
Dim itemOffset As Integer = e.NumberOfItems
Dim NumberOfItems As Integer = 1000000000
Dim Take As Integer = 20
For i As Integer = 0 To Take
ComboBox.Items.Add(New Telerik.Web.UI.RadComboBoxItem(i + itemOffset, (i + itemOffset).ToString))
Next
Dim NumberOfItemsInComboBox As Integer = e.NumberOfItems + ComboBox.Items.Count
If NumberOfItems > 0 Then
e.Message = [String].Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", NumberOfItemsInComboBox, NumberOfItems)
Else
e.Message = "No matches"
End If
e.EndOfItems = (NumberOfItemsInComboBox >= NumberOfItems)
End Sub
Protected Sub rlv_ItemInserting(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadListViewCommandEventArgs) Handles rlv.ItemInserting
Dim ComboBox As Telerik.Web.UI.RadComboBox = e.ListViewItem.FindControl("RadComboBox1")
If Not String.IsNullOrWhiteSpace(ComboBox.SelectedValue) Then
Dim UserID As Integer = ComboBox.SelectedValue
Dim UserName As String = ComboBox.Text
Me.Users.Add(New UserInfo(UserID, UserName))
Else
e.Canceled = True
End If
End Sub
<Serializable()>
Public Class UserInfo
Private _UserID As Integer
Private _UserName As String
Public ReadOnly Property UserID As Integer
Get
Return _UserID
End Get
End Property
Public ReadOnly Property UserName As String
Get
Return _UserName
End Get
End Property
Public Sub New(ByVal UserID As Integer, ByVal UserName As String)
_UserID = UserID
_UserName = UserName
End Sub
End Class
End Class
After you have inserted the new item, set the InsertItemPosition to None:
RadListView1.InsertItemPosition = RadListViewInsertItemPosition.None
radlistview1.IsItemInserted=false;
or set e.canceled=false after save click
I am using nested repeaters with Dataset (not using Datatable) to retrieve information by passing parameters. So far I have bind the two repeaters clearly and everything is working fine.
Here the list of messages created by each user datawise(parameter passed) will be displayed, and there could be more than 50 messages created by each user daily. So now I want to do custom paging for each user.
But I am unable to proceed further, as the next, previous, back, first links are placed inside the child repeaters footer template and I couldn't access these links even by findcontrol method.
Example:
User1
No Msg Code
1 abcd Cl-6
2 some Cl-4
3 swedf Cl-3
4 sddf Cl-1
1,2,3,4,5 (Paging)
User2
No Msg Code
1 dgfv Cl-96
2 abcd Cl-4
3 sjuc Cl-31
4 liot Cl-1
1,2,3,4,5 (Paging)
In this ways goes for every user:
Public Sub CreateNestedRepeater()
Dim strSql_1 As String, strsql_2 As String
Dim strCon_1 As New SqlConnection
Dim strCon_2 As New SqlConnection
Dim ds As New DataSet()
frmDate = AMS.convertmmddyy(txtFromDate.Text)
toDate = AMS.convertmmddyy(txtToDate.Text)
strCon_1 = New SqlConnection(ConfigurationManager.ConnectionStrings("connectionString").ConnectionString)
strSql_1 = "select User_Login, User_Id from V_mst_UserMaster Where User_Flag = 1 and User_Type='CO'"
Dim daCust As New SqlDataAdapter(strSql_1, strCon_1)
daCust.Fill(ds, "RptCoord_Name")
WhereClause1 = "where MsgHdr_Id NOT IN (Select a.MsgHdr_Id from V_AMS_GetSentMsg as a Join V_AMS_GetSentMsg as b " _
& "on a.MsgHdr_Id = b.MsgHdr_PrevMsgId) and MsgHdr_Date >= '" & frmDate & "' and MsgHdr_Date <= '" & toDate & _
"'AND MsgHdr_MsgFlag='I' and MsgHdr_AckReq <> 'N'"
OrderBy = "order by MsgHdr_Date asc"
strCon_2 = New SqlConnection(ConfigurationManager.ConnectionStrings("conn_Ind_AKK_TRAN").ConnectionString)
strsql_2 = "select User_Login,MsgHdr_Date, Client_Code, MsgHdr_RefNo, MsgType_Name, MsgHdr_Subject " _
& " from V_AMS_GetSentMsg " & WhereClause1 & OrderBy
Dim daOrders As New SqlDataAdapter(strsql_2, strCon_2)
daOrders.Fill(ds, "RptCd_Record")
Dim rel As New DataRelation("CrdRelation", ds.Tables("RptCoord_Name").Columns("User_Login"), ds.Tables("RptCd_Record").Columns("User_Login"), False)
ds.Relations.Add(rel)
rel.Nested = True
Rep1.DataSource = ds.Tables("RptCoord_Name").DefaultView
Rep1.DataBind()
strCon_1.Close()
strCon_2.Close()
End Sub
Protected Sub Rep1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles Rep1.ItemCommand
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
DirectCast(e.Item.FindControl("Rep2"), Repeater).DataSource = DirectCast(e.Item.DataItem, DataRowView).CreateChildView("CrdRelation")
DirectCast(e.Item.FindControl("Rep2"), Repeater).DataBind()
End If
End Sub
Protected Sub Pagging(ByVal index As Integer)
Dim PDS As New PagedDataSource
PDS.DataSource = ds.Tables("RptCoord_Name").DefaultView
PDS.CurrentPageIndex = index
PDS.AllowPaging = True
PDS.PageSize = 4
Dim rep2 As Repeater = CType(e
rep2.DataSource = PDS
Rep2.DataBind()
Dim ddl As DropDownList = DirectCast(rep2.Controls(rep2.Controls.Count - 1).FindControl("PageCount"), DropDownList)
If ddl IsNot Nothing Then
For i As Integer = 1 To PDS.PageCount - 1
ddl.Items.Add(i.ToString())
Next
End If
End Sub
Public Sub PageIndex(ByVal sender As Object, ByVal e As EventArgs)
Dim ddl As DropDownList = DirectCast(rep2.Controls(rep2.Controls.Count - 1).FindControl("PageCount"), DropDownList)
Pagging(Integer.Parse(ddl.SelectedItem.Text) - 1)
End Sub
XML:
<asp:Repeater id="Rep1" runat="server" OnItemCommand="Rep1_ItemCommand" EnableViewState = "false" >
<ItemTemplate>
<table width="100%" border="0.8" cellpadding="0" cellspacing="0" CssClass="bodytext" >
<tr><td align="center" class="RepHeader" >
Incoming Messages - Pending Ack for
<%#getUser(DataBinder.Eval(Container.DataItem, "User_Login"))%> from <%= txtFromDate.Text %>
to <%=txtToDate.Text%>
<%-- OnItemDataBound="Rep2_ItemDataBound" --%>
<asp:Repeater id="Rep2" runat="server" datasource='<%#(Container.DataItem).Row.GetChildRows("CrdRelation") %>' >
<HeaderTemplate>
<table border="1" width="100%" >
<tr class="RepHeader" >
<td>Msg Date</td><td>CL Code</td><td>INCRefNo</td><td>Contents</td><td>Subject</td></tr></HeaderTemplate><ItemTemplate>
<tr class="RrpList">
<td><%#getdate(CType(Container.DataItem, System.Data.DataRow)("MsgHdr_Date"))%> </td>
<td><%#CType(Container.DataItem, System.Data.DataRow)("Client_Code")%> </td>
<td><asp:LinkButton ID="lnkRef" runat="server"></asp:LinkButton>
<a id="hrefRefNo" runat="server" href="#" class="Link" >
<%#CType(Container.DataItem, System.Data.DataRow)("MsgHdr_RefNo")%></a></td>
<td><%#CType(Container.DataItem, System.Data.DataRow)("MsgType_Name")%> </td>
<td><%#CType(Container.DataItem, System.Data.DataRow)("MsgHdr_Subject")%> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
<%--Starts Here - (Paging for Pending Nested Repeaters) --%>
<tr align="center" class = "RepHeader">
<td colspan="5">
<asp:LinkButton ID="lnkFirst" runat="server" ForeColor="Black" Text="First" >
</asp:LinkButton>
<asp:LinkButton ID="lnkPrevious" runat="server" ForeColor="Black" Text="Previous" >
</asp:LinkButton> Now Showing Page
<asp:DropDownList ID="ddlpageNumbers" runat="server" AutoPostBack="true" >
</asp:DropDownList> of <asp:Label ID="lblTotalPages" runat="server"> </asp:Label>
Pages.
<asp:LinkButton ID="lnkNext" runat="server" ForeColor="Black" Text="Next" >
</asp:LinkButton>
<asp:LinkButton ID="lnkLast" runat="server" ForeColor="Black" Text="Last" >
</asp:LinkButton>
</td> </tr>
<%--Ends Here (Paging for Pending Nested Repeaters)--%>
</td></tr>
<br />
</table>
</FooterTemplate>
</asp:Repeater>
</ItemTemplate>
<SeparatorTemplate><br /><br /></SeparatorTemplate>
</asp:Repeater>
I couldn't understand how to do paging.
You shroud read about it:
http://idunno.org/archive/2004/10/30/145.aspx
http://support.microsoft.com/kb/306154