I have a page from where a user can search for items and so on. I use a .ascx page to display the result in a grdview.
The aspx page only has a seacrh box and a button and on button click I want to pass the value from inside the textbox to the ascx page and have the gridview populate with the result. But after debugging I found that the gridview is set to null after the button click. All other values are there and the result comes back from the database.
Can some one please help. I have been looking for a solution for last few hours and have treid a few diffeerent things but still not getting anywhere.
thanks in advance
EDIT
Here is my code
This is the aspx page.
<%# Register Src="Search.ascx" TagName="Search" TagPrefix="uc1" %>
<form id="form1" runat="server">
<div class="content">
<div style="padding:5px;">
<b>Search</b>: <asp:TextBox runat="server" ID="txtSearch" />
<asp:RequiredFieldValidator ErrorMessage="*" ValidationGroup="SearchGroup" ControlToValidate="txtSearch" ID="RequiredFieldValidator1"
runat="server" />
</div>
<div style="padding:5px;">
<asp:Button Text="Search" runat="server" ValidationGroup="SearchGroup" OnClick="btnSearch_Click" ID="btnSearch" />
</div>
</div>
<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<div class="Results">
<uc1:Search ID="UserControl1" runat="server" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
In the ASCX page I have the following
The code behind
Dim test As Object = txtSearch.Text
Dim StockList As cls_Stock_Col = MyLOTSDB.LoadStock_Col()
Try
Dim dt As DataTable = New DataTable()
Dim dcol As New DataColumn("TradeName", GetType(System.String))
dt.Columns.Add(dcol)
'Create an ID column for adding to the Datatable
dcol = New DataColumn("PackSize", GetType(System.String))
dt.Columns.Add(dcol)
dcol = New DataColumn("PLU", GetType(System.String))
dt.Columns.Add(dcol)
dcol = New DataColumn("SOH", GetType(System.String))
dt.Columns.Add(dcol)
dcol = New DataColumn("RetailAsCurrency", GetType(System.String))
dt.Columns.Add(dcol)
For Each col As DataColumn In dt.Columns
'Declare the bound field and allocate memory for the bound field.
Dim bfield As New BoundField()
'Initalize the DataField value.
bfield.DataField = col.ColumnName
'Initialize the HeaderText field value.
Dim DisplayName As String = ""
Dim DataFormat As String = ""
Dim FieldType As Type = col.GetType()
Dim StringLength As Int32
GetFieldDetails(TheType, col.ColumnName, DisplayName, DataFormat, FieldType, StringLength)
bfield.HeaderText = DisplayName
If (DataFormat = "$0.00") Then
bfield.DataFormatString = "{0:C2}"
End If
bfield.SortExpression = "col.ColumnName"
'Add the newly created bound field to the GridView.
GridView1.Columns.Add(bfield)
Next
GridView1.DataSource = StockList
GridView1.DataBind()
Catch ex As Exception
End Try
I can debug and the error is thrown when I try to add the column to the gridview,
Thanks again
The aspx page only has a seacrh box and a button and on
button click I want to pass the value from inside the textbox to the ascx page
You can do this by specifying a public property on your ascx control which you can access on calling page.
Inside your ascx code behind
private string searchText ;
Public string SetSearchText
{
get { return searchText; }
set { return searchText; }
}
In your calling page on button click, just set the property of the ascx control
Inside your main page on button click
YourAscxControl.SetSearchText= yourTextBox.Text.Trim();
User Dynamic Content Place Holder .
Refer to following links they might help:-
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
http://www.codeproject.com/Articles/18080/Solve-Dynamic-Control-Problem-With-PostBack
Related
What I am attempting to achieve is basically this:
user clicks on save as button
dialog "pop-up" shows that has report categories and name entry
user enters a name, or selects category which loads old reports
backend will get the values from dialog and use those to update reports in database
My issue is that when I fire the MyTreeView.SelectedNodeChanged event, I am redirected to the aspx page that I'm showing in my dialog pop-up. Is there anything I can do to prevent this, or contain the postback? I included my code, but I'm guessing this will be something I will have to account for in aspx?
Here's some code:
ReportSave.aspx -- in dialog window
<%# Page Language="VB" AutoEventWireup="false" CodeFile="ReportSave.aspx.vb" Inherits="ReportSave" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Save Report As</title>
<link href="ReportSaveStyle.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form id="formReportSave" runat="server">
<div class="container">
<asp:Label class="report-list-title" ID="lblReportList" runat="server" Text="Report List"></asp:Label>
<asp:TreeView class="report-list-items" ID="trvReportList" runat="server"></asp:TreeView>
<asp:Label class="category-tree-title" ID="lblReportCategory" runat="server" Text="Report Category"></asp:Label>
<asp:TreeView class="category-tree-items" ID="trvCategoryView" runat="server"></asp:TreeView>
<asp:Label class="save-input-title" ID="lblReportName" runat="server" Text="Report Name"></asp:Label>
<asp:TextBox class="save-input-textbox" ID="tbReportName" runat="server"></asp:TextBox>
<asp:Button class="save-button1" ID="btnOK" runat="server" Text="OK" />
<asp:Button class="save-button2" ID="btnCancel" runat="server" Text="Cancel" />
</div>
</form>
</body>
</html>
Backend code - ReportSave.aspx.vb
Private Sub trvCategoryView_SelectedNodeChanged(sender As Object, e As EventArgs) Handles trvCategoryView.SelectedNodeChanged
Try
'Dim li As ListItem
'li = cblCategoryView.SelectedItem
Dim node As TreeNode
node = trvCategoryView.SelectedNode
' handle all categories
If node.Value.ToString.ToUpper = "NEW CATEGORY" Then
Dim strNC As String = InputBox("Enter Name for New Category", "Create Category")
If strNC = "" Then
Exit Sub
End If
If strNC.ToUpper = "NEW CATEGORY" Then
ClientScript.RegisterStartupScript(Me.GetType(), "myalert", "window.alert('You can't have a Category Called New Category. Sorry!');", True)
Exit Sub
End If
Dim conn As New SqlClient.SqlConnection(_ConnectionString)
conn.Open()
Dim cmd As New SqlClient.SqlCommand("Select recordno from Reports where ReportType = '" & strNC & "'", conn)
Dim strresult As String = cmd.ExecuteScalar
If IsNothing(strresult) Then
Dim temp As TreeNode = New TreeNode(strNC, strNC, "Images/file.png")
' Dim temp As ListItem = New ListItem(strNC, strNC)
'lvCategoryView.Items.Add(temp)
'SetSelectedListItem(lvCategoryView.Items(lvCategoryView.Items.Count - 1))
'cblCategoryView.Items.Add(temp)
trvCategoryView.Nodes.Add(temp)
FillReports()
lblReportList.Text = "Report List for Group " & trvCategoryView.SelectedValue.ToString
' cblCategoryView.SelectedValue
ClientScript.RegisterStartupScript(Me.GetType(), "myalert", "window.alert('That Report Group Already Exists');", True)
End If
cmd.Dispose()
cmd = Nothing
conn.Close()
conn.Dispose()
conn = Nothing
Exit Sub
Else
'SetSelectedListItem(li)
FillReports()
lblReportList.Text = "Report List for Group " & trvCategoryView.SelectedValue.ToString
'cblCategoryView.SelectedValue.ToString
End If
Catch ex As Exception
End Try
End Sub
Thanks for any help in advance! I am new to Web Development as well as ASP.NET. :)
I am making the assumption that you are loading this form into an iframe, and would guess that the problem lies in the implementation of the MyTreeView.SelectedNodeChanged event or the parent page itself.
Thinking outside the box, Web Forms may have alternate solutions to accomplish your objectives. The implementation of an iframe would be my least favorite. Depending on your specific requirements, these options may work better for you.
Nested Masterpages
Re-usable User Control (ascx) in overlay (popup) DIV element
Update Panel in overlay (popup) DIV element
AJAX post to Handler (ashx)
I have a non content (no master) page with a repeater that performs as I want it to, but when I move the same code to a content page (with master), the findControl in a loop of RepeaterItems no longer works.
aspx:
<ItemTemplate>
<div class="row" id="qrow" runat="server" data-id='<%#Eval("callQuestionID") %>' data-type='<%#Eval("callQuestionResponseType") %>' data-parent='<%#Eval("callQuestionParent") %>'>
<div class="col-md-4">
<asp:Label ID="questonTextLabel" runat="server" Text='<%# Eval("callQuestionText") %>'></asp:Label>
</div>
<div class="col-md-4">
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
</div>
</ItemTemplate>
ItemDataBound exerp
Dim newRBY As New RadioButton
newRBY.InputAttributes.Add("data-id", CType(e.Item.DataItem, DataRowView)("callQuestionID"))
newRBY.InputAttributes.Add("data-idy", CType(e.Item.DataItem, DataRowView)("callQuestionID"))
newRBY.ID = "rby"
newRBY.Text = "Yes"
newRBY.GroupName = "qid" & CType(e.Item.DataItem, DataRowView)("callQuestionID")
CType(e.Item.FindControl("Panel1"), Panel).Controls.Add(newRBY)
Dim newRBN As New RadioButton
newRBN.InputAttributes.Add("data-id", CType(e.Item.DataItem, DataRowView)("callQuestionID"))
newRBN.InputAttributes.Add("data-idn", CType(e.Item.DataItem, DataRowView)("callQuestionID"))
newRBN.ID = "rbn"
newRBN.Text = "No"
newRBN.GroupName = "qid" & CType(e.Item.DataItem, DataRowView)("callQuestionID")
CType(e.Item.FindControl("Panel1"), Panel).Controls.Add(newRBN)
Post user interaction processing:
For Each questionRow As RepeaterItem In questionRepeater.Items
...
Dim rby As RadioButton = CType(questionRow.FindControl("rby"), RadioButton) ****** Fails Here *****
If rby.Checked Then
dataAccess.callQuestionAnswerTable_Insert(callIDInteger, CInt(rby.InputAttributes("data-id")), "true")
ElseIf CType(questionRow.FindControl("rbn"), RadioButton).Checked Then
dataAccess.callQuestionAnswerTable_Insert(callIDInteger, CInt(rby.InputAttributes("data-id")), "false")
End If
It fails in the post user interaction processing when trying to find 'rby'. The only difference in generated HTML is that in the content page the controls ids get a MainContent_ prefix.
What can I do to resolve this?
If the code is located on the child page, while the Repeater is located on the Master Page itself, you need to specify the Master page with FindControl and locate the Repeater there.
Dim rpt As Repeater = CType(Master.FindControl("Repeater1"),Repeater)
And then
For Each questionRow As RepeaterItem In rpt.Items
(translated from C# to VB with a code translator, so it may be a little off, in C# it is Repeater rpt = Master.FindControl("Repeater1") as Repeater;)
I found my problem. It was actually that I had the binding of the repeater in a
If Not IsPostBack Then
block and I should not have apparently.
I'm not sure how ASP.NET works since I'm still very new to it, coming from a PHP background where most things are done with POST. I'm using VB.NET behind the code. Mainly because the main program used here is written in VB.NET and I want to keep the code portable without compiling a library.
My issue is as follows. I have a DropDownList on the page. I populate it with data from the database. That seems to work fine.
I have a button that should change the CLIENTCODE to whatever has been selected in the DropDownBox. This doesn't work. Instead the Index is always -1.
Page Code
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/MasterPage.Master" CodeBehind="Admin.aspx.vb" Inherits="WOTC_CP.Admin" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="RightBody" runat="server">
<%
Load_UserList_List()
%>
<h1 class="sub-header">Administration Toolbox</h1>
<p>If you are not an Administrator, please send us an alert and leave this page at once.</p>
<div class="row">
<div class="form-group">
<div class="col-md-4">
<asp:Label ID="Label1" runat="server" Text="Label">Change my Clientcode;</asp:Label>
<asp:DropDownList ID="cboClientList" class="form-control" runat="server" >
</asp:DropDownList>
<asp:Button ID="cmdChangeClientCode" class="btn btn-primary" runat="server" Text="Change" />
</div>
</div>
</div>
Behind Code
Public Sub Load_CLIENTCODE_List()
If IsPostBack = False Then
Using DB As New wotcDB
Dim r = (From t In DB.client_main Order By t.CLIENTCODE Select t.CLIENTCODE).Distinct
For Each Client In r
Dim input As New ListItem
input.Text = Client
input.Value = Client
cboClientList.Items.Add(input)
Next
End Using
End If
End Sub
Private Sub cmdChangeClientCode_Click(sender As Object, e As EventArgs) Handles cmdChangeClientCode.Click
Dim CLIENTCODE As String = CType(Session("CLIENTCODE"), String)
Dim UserName As String = CType(Session("UserName"), String)
Using DB As New wotcDB
Dim u = (From t In DB.website_users Where t.UserName = UserName).FirstOrDefault
If u IsNot Nothing Then
Dim TempID As Integer = cboClientList.SelectedIndex
Dim TempValue As String = cboClientList.SelectedValue
u.CLIENTCODE = cboClientList.SelectedValue
DB.SaveChanges()
End If
End Using
End Sub
I've tried other answers here on stack, but nothing seems to work. Any Ideas?
In asp.net the dropdown list has two key properties that you want to set. DataTextField = Display Name and DataValueField = value to store to DB.
With that said, you need to capture the "SelectedValue" if you want to get the DataValueField.
The issue was that I was loading the script that populated the DropDownList before getting it's value. So it was always empty. The solution was to load the list on Page_Load instead.
VS 2013, ASP.NET 3.5 VB.NET
Page has multiple ModalPopupExtender controls for different popups. One of these popups fills a table with CheckBoxControls and descriptions for up-selling items.
Page Code:
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
[snip]
<ajax:ModalPopupExtender
runat="server"
ID="mpeUpsell"
popupControlID="pUpsell"
CancelControlID="bGoBack"
BackgroundCssClass="custBackground"
PopupDragHandleControlID="phDragUpsell"
TargetControlID="bHidden"
Enabled="True" />
<asp:Panel runat="server" ID="pUpsell" style="display:none;">
<div runat="server" class="custPopup">
<div runat="server" id="phDragUpsell">
<h3 style="text-align:center;">
<asp:Label
ID="lUpsellHdr"
runat="server"
Text="Check Out these Add-Ons" />
</h3>
</div>
<asp:Label
ID="lAddOnsText"
runat="server" />
[snip]
<asp:Table
ID="tItems"
runat="server"
style="border: 1px solid black;">
[snip] <asp:Button ID="bNext" runat="server" Text="Next --->" />
</td>
</tr>
</table>
<br />
<br />
</div>
</asp:Panel>
The table tItems is populated like so:
For Each dr As DataRow In ds.Tables(0).Rows
tr = New TableRow()
tc = New TableCell()
Dim sName As String = "cbItem_" & CInt(dr("ITEM_ID"))
Dim cb As New CheckBox()
cb.ID = sName
cb.Text = dr("ITEM_DESC").ToString.Trim
If CInt(dr("UGICheckOFF")) = 1 Then
cb.Checked = True
Else
cb.Checked = False
End If
[snip formatting]
tc.Controls.Add(cb)
tr.Cells.Add(tc)
tc2 = New TableCell()
Dim sPrice As String = String.Format("{0:C}", dr("ITEM_PRICE"))
tc2.Text = sPrice
[snip formatting]
tr.Cells.Add(tc2)
tItems.Rows.Add(tr)
Next
The table populates perfectly and shows when I use code-behind to show the mpeUpsell ModalPopupExtender.
The bNext button's handler looks like this:
Protected Sub bNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles bNext.Click
If iItemArray IsNot Nothing Then iItemArray = Nothing ' get rid of it
' Handle the Next Button
Dim iCartID As Integer = -1
iCartID = CInt(Session("CartID"))
' iterate the items and add each to cart if not already in cart
iItemArray = New ArrayList()
For Each tr As TableRow In tItems.Rows
For Each tc As TableCell In tr.Cells
For Each ctl As Control In tc.Controls
If TypeOf (ctl) Is CheckBox Then
Dim cb As CheckBox = CType(ctl, CheckBox)
If cb.Checked Then
'if there are checks create array of item IDs checked.
Dim itemid As Integer = CInt(cb.ID.Replace("cbItem_", ""))
iItemArray.Add(itemid)
End If
End If
Next
Next
Next
[snip]
End Sub
When the handler is executed, tItems.Rows.Count is ZERO and the ForEach simply falls through because the table rows are gone.
It is obvious that I have missed something; I just cannot figure out what I have missed.
Thanks,
John.
The solution was to abandon the asp table because it is not stateful in this instance. Instead, I used a gridview and bound a datatable to it, and am able to retrieve the values.
Thanks.
So, I'm having a slight problem with my code.
I was working on a small school project (recreation of book library) and encountered a problem which I cannot get a grasp of.
So, the user can search for a list of books, and after the list is populated (via DataList control), a small button "Book now" (Reserve) appears which user can click and reserve his book.
This is the code for the DataList control that resides in "Search.aspx"
<asp:DataList ID="DataList1" runat="server" DataKeyField="knjigaId" DataSourceID="SearchSqlDataSource" CssClass="searchControl">
<ItemTemplate>
<div class="pictureOfFoundBook">
<asp:Image ID="pictureOfFoundBook_imageLink" runat="server" ImageUrl='<%#"~/GetImage.aspx?knjigaId=" & Eval("knjigaId") & "&img=naslovnica" %>' />
</div>
<div class="descriptionOfFoundBook">
Naziv: <asp:Label ID="Label1" runat="server" Text='<%# Eval("naziv") %>' /><br />
Godina izdanja: <asp:Label ID="Label2" runat="server" Text='<%# Eval("godinaIzdanja") %>' /><br />
Broj stranica : <asp:Label ID="brojStranicaLabel" runat="server" Text='<%# Eval("brojStranica") %>' /><br />
Izdavač: <asp:Label ID="NazivIzdavacaLabel" runat="server" Text='<%# Eval("NazivIzdavaca") %>' /><br />
Vrsta tiskovine : <asp:Label ID="NazivVrsteTiskovineLabel" runat="server" Text='<%# Eval("NazivVrsteTiskovine") %>' /><br />
Kategorija: <asp:Label ID="NazivKategorijeLabel" runat="server" Text='<%# Eval("NazivKategorije") %>' /><br /><br />
<asp:HyperLink ID="foundBookEditHL_adminOnly" runat="server" NavigateUrl='<%# "~/admin/knjigeEdit.aspx?knjigaId=" & Eval("knjigaId") %>'>Uredi knjigu</asp:HyperLink><br />
<asp:Button ID="rezervacijeButton" runat="server" Text="Rezerviraj" OnClick="rezervacijaClick" CommandArgument='<%# Eval("knjigaId") %>'/><br />
<asp:Label ID="rezStatusLabel" runat="server"></asp:Label>
<asp:PlaceHolder ID="rezStatusPlaceholder" runat="server"></asp:PlaceHolder>
</div>
<hr />
</ItemTemplate>
</asp:DataList>
I've set the DataList1 control as a Friend sub so I can access the controls in it from another sub;
Friend Sub DataList1_ItemCreated(sender As Object, e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList1.ItemCreated
End Sub
I was trying to do the following; on the click of a button "rezervacijeButton", a function "rezervacijaClick" runs, which populates the table in the database.
Protected Sub rezervacijaClick(sender As Object, e As System.EventArgs)
Dim Conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("LocalSqlServer").ToString)
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim sql As New StringBuilder
Dim rezstatus As Label = DataList1.FindControl("rezStatusLabel")
sql.Append("INSERT INTO rezervacije(UserName, knjigaId) VALUES (#UserName, #knjigaId)")
Dim buttonsender As Button = sender
cmd.Parameters.AddWithValue("UserName", User.Identity.Name)
cmd.Parameters.AddWithValue("knjigaId", buttonsender.CommandArgument)
Conn.Open()
cmd.CommandText = sql.ToString
cmd.Connection = Conn
cmd.ExecuteNonQuery()
Conn.Close()
buttonsender.Visible = False
rezstatus.Text = "aaa"
'Try
' rezstatus.Text = "testing..."
'Catch ex As Exception
' exlabel.Text = "POGREŠKA"
' exlabel.ForeColor = Drawing.Color.Red
'End
End Sub
The next thing I wanted to do in the function "rezervacijaClick" was to set the text value of the Label (with ID "rezStatusLabel", which resides inside the DataList1 control) to "SOME TEXT" after the "Reserve" button is clicked.
But after the button click, I get the following error :
Object reference not set to an instance of an object.
Line 21:
Line 22: buttonsender.Visible = False
Line 23: rezstatus.Text = "aaa"
Line 24:
Line 25: 'Try
Your rezstatus object is Nothing (null).
This is happening because you aren't looking in the right place for your label.
Each record of data you bind to the DataList will create a new hierarchy of controls, containers that hold the other controls you have defined in your ItemTemplate.
The immediate descendants of DataList1 will be a collection of DataListItem objects and then you will have your controls inside those.
Since we don't know for sure (unless you know you are only binding one record to the DataList) which DataListItem the desired label will be in, we simply walk backwards up the control tree and find the label from there.
Because you are responding to a button click event in your rezervacijaClick method, the parameter sender will be of type Button and will come from rezervacijeButton, so we can use that information to find your label:
Dim clickedButton As Button = CType(sender, Button) 'convert the sender parameter to the correct type: Button
Dim buttonParent As Control = clickedButton.Parent 'get a reference to the button's parent control
Dim rezstatus As Label = CType(buttonParent.FindControl(""), Label) 'find the label by ID and convert it to a Label as the return type of FindControl is Control
I would recommend that, instead of using the Button click event, you use the DataList.ItemCommand event. It will make your life a lot easier. This event fires whenever a Button is clicked within a row of your DataList control.
This way, you get the index passed in through the DataListCommandEventArgs parameter. then you would just need to update your DataList markup to add the event handler:
<asp:DataList ID="DataList1" runat="server" DataKeyField="knjigaId"
DataSourceID="SearchSqlDataSource" CssClass="searchControl"
ItemCommand="DataList1_ItemCommand" >
And your handler code would look like this:
Protected Sub DataList1_ItemCommand(sender As Object, e As System.EventArgs)
Dim Conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("LocalSqlServer").ToString)
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim sql As New StringBuilder
Dim rezstatus As Label = e.Item.FindControl("rezStatusLabel")
sql.Append("INSERT INTO rezervacije(UserName, knjigaId) VALUES (#UserName, #knjigaId)")
Dim buttonsender As Button = e.Item.FindControl("rezervacijeButton")
cmd.Parameters.AddWithValue("UserName", User.Identity.Name)
cmd.Parameters.AddWithValue("knjigaId", buttonsender.CommandArgument)
Conn.Open()
cmd.CommandText = sql.ToString
cmd.Connection = Conn
cmd.ExecuteNonQuery()
Conn.Close()
buttonsender.Visible = False
rezstatus.Text = "aaa"
End Sub