Add data to gridview, from textbox, on button click - asp.net

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

Related

Gridview not sorting

I've come across this strange error and it's been bugging me for hours now.
I've got some LinkButtons on my screen and depending on which button the user chooses a label's text is set, a GridView is displayed and the Datasource of this GridView is assigned based on the text of the label.
This all works fine and dandy. However the problem arises when I want to sort this GridView.
At the moment, nothing happens. When I attempt to sort a column the page just refreshes and I'm left with the same unsorted mess in my GridView.
I've put my application into debug mode with breakpoints along the way and noticed that when I get to this step (the full code can be seen at the bottom of this post) :
senderGridView.SortExpression = button.CommandArgument
the senderGridView.SortExpression is "" so for some reason it's not passing the sort expression.
Hopefully somebody can enlighten me as to why my grid isn't sorting as I'm sure it's just a stupid mistake somewhere but any help would be appreciated, thanks.
Code that you may require...
My sub that sets the sort images when a row is created can be seen below:
Protected Sub GridViewSortImages(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim senderGridView As GridView = CType(sender, GridView)
'Loop through each cell in header row
For Each cell As TableCell In e.Row.Cells
If cell.HasControls Then
Dim button As LinkButton = TryCast((cell.Controls(0)), LinkButton)
Dim gv As New HtmlGenericControl("div")
Dim lnkName As New Label()
'Test cell to see if a link button exists (i.e. Allow Sorting = True)
If Not (button Is Nothing) Then
'Create new label and image and set to standard unsorted view
lnkName.Text = button.Text
Dim image As New System.Web.UI.WebControls.Image
image.ImageUrl = "images/sort-1x1.png"
image.ToolTip = "Sort"
image.AlternateText = "Sort"
'Test to see if grid is already sorted, and apply relevant image & tooltip
If senderGridView.SortExpression = button.CommandArgument Then
If senderGridView.SortDirection = SortDirection.Ascending Then
image.ImageUrl = "images/sort-asc.png"
image.ToolTip = "Sort Descending"
image.AlternateText = "Sort Descending"
Else
image.ImageUrl = "images/sort-desc.png"
image.ToolTip = "Sort Ascending"
image.AlternateText = "Sort Ascending"
End If
End If
'Add label and image to new div
gv.Controls.Add(lnkName)
gv.Controls.Add(image)
'Replace original column header with new div
button.Controls.Add(gv)
End If
End If
Next
End Sub
My RowCreated sub for the GridView...
Protected Sub grvHomeRisk_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles grvHomeRisk.RowCreated
If Not (e.Row Is Nothing) AndAlso e.Row.RowType = DataControlRowType.Header Then
GridViewSortImages(sender, e) 'Call sort code
End If
End Sub
My Sorting sub...
Protected Sub grvHomeRisk_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grvHomeRisk.Sorting
Select Case lblBreachHeaderb.Text
Case "Current Risks"
grvHomeRisk.DataSource = SQLDS_ListCurrentRisk
Case "All Risks Overdue"
grvHomeRisk.DataSource = SQLDS_ListAllRiskOverdue
Case "My Risks"
grvHomeRisk.DataSource = SQLDS_ListMyRisk
Case "My Risks Overdue"
grvHomeRisk.DataSource = SQLDS_ListRiskOverdue
Case "Risks Requested to Score & Re-Score"
grvHomeRisk.DataSource = SQLDS_ListScores
Case "Risks Requested to Score"
grvHomeRisk.DataSource = SQLDS_ListRiskScores
Case "Risks Requested to Re-Score"
grvHomeRisk.DataSource = SQLDS_ListRiskReScores
End Select
grvHomeRisk.DataBind()
End Sub
My GridView...
<asp:GridView ID="grvHomeRisk" runat="server" AutoGenerateColumns="false" AllowSorting="true"
CssClass="GridMain" UseAccessibleHeader="false"
ForeColor="#333333" GridLines="None" Width="780px" BorderWidth="0px"
AllowPaging="true" PageSize="5" CellPadding="3" DataKeyNames="IDRISK">
<Columns>
<asp:CommandField ButtonType="Image" SelectText="View Risk" ShowSelectButton="True" SelectImageUrl="~/Images/button-select1.png" />
<asp:BoundField DataField="TXRISKSUMMARY" HeaderText="Risk" ReadOnly="True" />
<asp:BoundField DataField="TSRISKSTART" HeaderText="Start Date" ReadOnly="True" DataFormatString="{0:dd MMM yyyy}" />
<asp:BoundField DataField="TSRISKREVIEW" HeaderText="Review Date" SortExpression="TSRISKREVIEW" ReadOnly="True" DataFormatString="{0:dd MMM yyyy}" />
<asp:BoundField DataField="TXUSER_NAME_O" HeaderText="Owner" SortExpression="TXUSER_NAME_O" ReadOnly="True" />
<asp:BoundField DataField="TXDESCRIPTION" HeaderText="Risk Element" SortExpression="TXDESCRIPTION" ReadOnly="True" />
<asp:BoundField DataField="TSDATMOD" HeaderText="Date Modified" ReadOnly="True" DataFormatString="{0:dd MMM yyyy}" />
<asp:BoundField DataField="TXUSER_NAME_M" HeaderText="Modified By" ReadOnly="True" />
</Columns>
<PagerTemplate>
<table>
<tr>
<td>
<asp:Button ID="FirstButton" runat="server" CommandArgument="First" CommandName="Page" Text="<<" CssClass="buttongrid" ToolTip="First" OnClientClick="needToConfirm = false;" />
<asp:Button ID="PrevButton" runat="server" CommandArgument="Prev" CommandName="Page" Text="Previous" CssClass="button" ToolTip="Previous" OnClientClick="needToConfirm = false;" />
</td>
<td>
<asp:Label ID="lblPageCount" runat="server" CssClass="TextA12Bold" Visible="false"></asp:Label>
</td>
<td>
<asp:Button ID="NextButton" runat="server" CommandArgument="Next" CommandName="Page" Text="Next" CssClass="button" ToolTip="Next" OnClientClick="needToConfirm = false;" />
<asp:Button ID="LastButton" runat="server" CommandArgument="Last" CommandName="Page" Text=">>" CssClass="buttongrid" ToolTip="Last" OnClientClick="needToConfirm = false;" />
</td>
</tr>
</table>
</PagerTemplate>
</asp:GridView>

How to get the current values of RadGrid Columns

I am using the follwing code.
in .aspx:
function AccessOnclient() {
debugger;
var grid = $find("<%= dg_InvPat.ClientID %>");
if (grid) {
var MasterTable = grid.get_masterTableView();
var sumtemp = 0;
var Rows = MasterTable.get_dataItems();
for (var i = 0; i < Rows.length; i++) {
var row = Rows[i];
var RadNumericTextBox1 = row.findControl("txt_projInv");
if (RadNumericTextBox1.get_value())
{
sumtemp =sumtemp + RadNumericTextBox1.get_value();
}
}
for (var i = 0; i < Rows.length; i++) {
var row = Rows[i];
var RadNumericTextBox1 = row.findControl("txt_projInv");
var valinv=RadNumericTextBox1.get_value();
var res=Math.round((valinv/sumtemp)*100);
var revpat = MasterTable.get_dataItems()[i].findElement("lbl_revpat");//access the Label control
revpat.innerText = res;
}
document.getElementById("ctl00_MainContent_b1").click();
}
}
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<div id="content">
<table class="table_Style" width="100%">
<tr>
<td style="width: 15%">
<asp:Label ID="Label2" runat="server">Financial Year</asp:Label>
</td>
<td>
<Telerik:RadComboBox AutoPostBack="true" runat="server" ID="ddl_year" Width="200px"
MarkFirstMatch="true" CausesValidation="true" ValidationGroup="List">
</Telerik:RadComboBox>
<asp:Button ID="cmd_go" runat="server" Text="View" CausesValidation="true"
ValidationGroup="btnSubmit"></asp:Button>
<asp:CompareValidator ID="cvyear" runat="server" ErrorMessage="Please Select Financial Year"
ControlToValidate="ddl_year" ValueToCompare="Select" Operator="NotEqual" ValidationGroup="btnSubmit"></asp:CompareValidator>
</td>
</tr>
</table>
<table class="table_Style" width="100%">
<tr>
<td>
<Telerik:RadGrid ID="dg_InvPat" runat="server" AutoGenerateColumns="False" GridLines="None"
HeaderStyle-VerticalAlign="Top" Width="100%" ShowStatusBar="True" AllowPaging="True"
AllowSorting="false" AllowFilteringByColumn="False" PageSize="5">
<GroupingSettings CaseSensitive="false" />
<ExportSettings ExportOnlyData="true" OpenInNewWindow="True" IgnorePaging="true"
FileName="InvPattern">
</ExportSettings>
<MasterTableView CommandItemDisplay="None" CommandItemSettings-ShowRefreshButton="false"
CommandItemSettings-ShowAddNewRecordButton="false">
<RowIndicatorColumn>
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>
<ExpandCollapseColumn>
<HeaderStyle Width="20px"></HeaderStyle>
</ExpandCollapseColumn>
<NoRecordsTemplate>
<font color="red">No Records Available</font>
</NoRecordsTemplate>
<Columns>
<Telerik:GridBoundColumn UniqueName="NOTIF1" DataField="NOTIF1" HeaderText="As Per Notification" Visible ="false" >
</Telerik:GridBoundColumn>
<Telerik:GridBoundColumn UniqueName="NOTIF" DataField="NOTIF" HeaderText="As Per Notification">
</Telerik:GridBoundColumn>
<Telerik:GridBoundColumn UniqueName="CAT" DataField="CAT" HeaderText="Pattern Category">
</Telerik:GridBoundColumn>
<Telerik:GridBoundColumn UniqueName="INVESTMENT" DataField="INVESTMENT" HeaderText="Act Investment">
</Telerik:GridBoundColumn>
<Telerik:GridBoundColumn UniqueName="LIMITID" DataField="LIMITID" HeaderText="Limit Id"
Visible="false">
</Telerik:GridBoundColumn>
<Telerik:GridBoundColumn UniqueName="TRUSTPAT1" DataField="TRUSTPAT1" HeaderText="Trust Pattern" Visible="false">
</Telerik:GridBoundColumn>
<Telerik:GridBoundColumn UniqueName="TRUSTPAT" DataField="TRUSTPAT" HeaderText="Trust Pattern">
</Telerik:GridBoundColumn>
<Telerik:GridBoundColumn UniqueName="SHORTAGE" DataField="SHORTAGE" HeaderText="Shortfall/Excess">
</Telerik:GridBoundColumn>
<Telerik:GridTemplateColumn HeaderText="Project Investment">
<ItemTemplate>
<Telerik:RadNumericTextBox ID="txt_projInv" runat="server" EmptyMessage="" IncrementSettings-InterceptMouseWheel="false"
SkinID="RadTextYellow" Type="Number" DataType="System.Int64"
AutoPostBack="false" MaxLength="8" Text='<%# Bind("investment") %>'>
<NumberFormat DecimalDigits="0" GroupSeparator="" />
<ClientEvents OnKeyPress="AccessOnclient" OnValueChanged="AccessOnclient"/>
</Telerik:RadNumericTextBox>
</ItemTemplate>
</Telerik:GridTemplateColumn>
<Telerik:GridTemplateColumn HeaderText="Revised Pattern">
<ItemTemplate>
<asp:Label ID="lbl_revpat" runat="server" Text='<%# Bind("trustpat1") %>'></asp:Label>
</ItemTemplate>
</Telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</Telerik:RadGrid>
</td>
</tr>
<tr id="tr1">
<td colspan="2">
<table width="100%" border="0" >
<tr>
<td align="center">
<br/>
<div id="divgraph1" runat="server" >
<asp:Panel ID="pnlnum" runat="server" Width="100%" Visible="False" style="height:400px">
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</asp:Panel>
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblhead" runat="server" Font-Size="10" ForeColor="#000033"
Font-Bold="True"></asp:Label>
</td>
<td align="right">
<asp:Label ID="lbltotal" runat="server" Font-Size="10" ForeColor="#000033"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label Width="100%" ID="lblmess" SkinID="lblErr" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button id="b1" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<Telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" DecoratedControls="Default"
Skin="Sunset" Style="margin-bottom: 0px" />
<Telerik:RadWindowManager ID="RadWindowManager2" ShowContentDuringLoad="false" VisibleStatusbar="false"
ReloadOnShow="true" runat="server" Modal="true">
</Telerik:RadWindowManager>
</td>
</tr>
</table>
</div>
</asp:Content>
in .aspx.vb:
#Region "Namespaces"
Imports Telerik.Web.UI
Imports System.Data
Imports System.Net
Imports System
Imports System.IO
Imports System.Text
Imports System.Net.Mail
Imports InfoSoftGlobal.InfoSoftGlobal
#End Region
Partial Class iv
Inherits System.Web.UI.Page
#Region "Declarations"
Dim objEntry_ml As ClsPF_BE
Dim objEntry_bll As ClsPF_BLL
Dim ds As DataSet
Dim objCom_ml As Common_ml
Dim objCom_bll As Common_bll
Dim UserSysId As Long
Public UnitID As Integer
Public UnitName As String
Dim strXML As String
#End Region
#Region "PageEvents"
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
AddHandler Master.PageEvent, AddressOf Page_Load
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Master.UnitChange = True Then
Response.Redirect("iv.aspx")
End If
Master.PageHeadingTitle = "Pattern"
If Not Session("UserSysId") Is Nothing Then
UnitID = Session("UnitId")
UnitName = Session("UnitName")
UserSysId = Session("UserSysId")
Else
Response.Redirect("Login.aspx?Status=S")
End If
If Not IsPostBack Then
LoadYear()
End If
lblmess.Text = ""
End Sub
Protected Sub cmd_go_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmd_go.Click
LoadGrid()
Literal1.Text = DrawGraph()
pnlnum.Visible = True
divgraph1.Visible = True
End Sub
Private Sub LoadGrid()
Dim ds As New DataSet
Try
objEntry_ml = New ClsPF_BE
objEntry_bll = New ClsPF_BLL
Dim sReturnMessage As String = ""
objEntry_ml.FinYear_code = ddl_year.SelectedValue
ds = objEntry_bll.bll_Invpattern(objEntry_ml, UserSysId, sReturnMessage)
dg_InvPat.DataSource = ds
dg_InvPat.DataBind()
ds = Nothing
If dg_InvPat.Items.Count > 1 Then
lblmess.Visible = False
divgraph1.Visible = True
Else
lblmess.Text = "No records found for the year" & ddl_year.Text
lblmess.Visible = True
End If
Catch ex As Exception
End Try
End Sub
Sub LoadYear()
objEntry_ml = New ClsPF_BE
objEntry_bll = New ClsPF_BLL
ds = objEntry_bll.fillfinyear(objEntry_ml)
ddl_year.DataSource = ds
If ds.Tables(0).Rows.Count > 0 Then
ddl_year.DataValueField = ds.Tables(0).Columns(0).Caption
ddl_year.DataTextField = ds.Tables(0).Columns(1).Caption
ddl_year.DataBind()
If ddl_year.Items.Count > 0 Then
ddl_year.Items.Insert(0, New RadComboBoxItem("Select", ""))
End If
End If
objEntry_ml = Nothing
objEntry_bll = Nothing
ds = Nothing
End Sub
#End Region
#Region "Functions"
Public Function DrawGraph() As String
Try
Dim ds As DataSet
Dim dv As DataView
Dim dr As DataRowView
Dim sReturnMessage As String = ""
objEntry_ml = New ClsPF_BE
objEntry_bll = New ClsPF_BLL
strXML = "<chart palette='4' pieSliceDepth='30' pieRadius='120' CAPTION='Investment Pattern(In %)' bgcolor='#e5e5e5' outCnvBaseFont='verdana' outCnvBaseFontSize='11' showPercentageValues='1' bgAngle='360' showBorder='1' baseFont='Arial' baseFontSize='11' baseFontColor ='000000'>"
For Each item As GridDataItem In dg_InvPat.Items
Dim txt As Label = DirectCast(item.FindControl("lbl_revpat"), Label)
Dim aa As String = txt.Text
strXML = (strXML & ("<set label='" & (Server.HtmlEncode(item.Cells(4).Text) & ("' value='" & aa & "'/>"))))
Next
strXML = (strXML & "</chart>")
Return FusionCharts.RenderChartHTML("FusionCharts/Charts/Pie3D.swf", "", Server.UrlEncode(strXML.ToString), "Percentage", "500", "350", False)
Catch ex As Exception
divgraph1.Visible = False
lblmess.Text = "You have no rights to view this report"
lblmess.ForeColor = Drawing.Color.Red
lblhead.Text = ""
lbltotal.Text = ""
End Try
End Function
#End Region
Protected Sub b1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles b1.Click
Literal1.Text = DrawGraph()
pnlnum.Visible = True
divgraph1.Visible = True
End Sub
End Class
Here when i chnge the textbox in templatecolumn in radgrid, the corresponding value is stored in the label(GridTemplateColumn of Radgrid). That is written in javascript. But the corresponding fusion chart is not shown. When i debug, the new values(calculated by javascript) are not taken into account. Only the values which is being bound in the grid will be plotted in the fusion chart.
In DrawGraph() function i have used the label named as Revised pattern(GridTemplateColumn) value as <set label value. But the new value is not coming.
Eg. if i give 600 in Project Investment column, the corresponding percentage 42 is coming in Revised pattern(GridTemplateColumn). But the fusion chart is not changed.
How the problem can be solved?
ANYONE PLEASE HELP ME.........
I suggest you to go for the textbox instead label
Because textbox are server control and label have problem always getting values
like if you are using update panel or so.....
so textbox will be a best option to use

Do a Button Click from Code behide

I have a gridview which lists Tools and Access values. To edit I have an edit imagebutton on each row. I have an OnRowBound method which assigns an OnClick attribute to each button so that I will know which record I need to edit.
The code is
Protected Sub ChangeFirstRowIcon(ByVal Sender As Object, ByVal e As GridViewRowEventArgs) Handles gv_AccessRights.RowDataBound
'This sub fires on each gridview row created...
'It first checks that the row is a data row (as opposed to Header, Footer etc.)
'If ib_Edit is true then change add an attribut to button with aid, tid and ac values attached.
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ib_Edit As ImageButton = e.Row.FindControl("ib_Edit")
Dim lb_AccessID As Label = e.Row.FindControl("lb_AccessID")
Dim hd_ToolID As HiddenField = e.Row.FindControl("hd_ToolID")
Dim hd_AccessCode As HiddenField = e.Row.FindControl("hd_AccessCode")
If ib_Edit IsNot Nothing Then
ib_Edit.Attributes.Add("onClick", "proxyClick('" & lb_AccessID.Text & "', '" & hd_ToolID.Value & "', '" & hd_AccessCode.Value & "')")
End If
End If
End Sub
I'm using a hidden proxy button to show a modal popup which the user will use to edit a record... (the same popup will be used to add a new access record... but that will come later). So having passed my details to proxyClick I set values to controls within the modal popup. The javascript is....
<script type="text/javascript">
function proxyClick(aid, tid, ac) {
document.getElementById('hd_AccessID').value = aid;
document.getElementById('hd_ToolIDMod').value = tid;
document.getElementById('hd_AccessCodeMod').value = ac;
document.getElementById('but_SetModalDetails').click();
}
</script>
For reference the main bits of the markup are....
<table class="border">
<tr>
<td>
<asp:Button ID="but_SetModalDetails" runat="server" Style="display: none" Text="Set modal details" ClientIDMode="Static" UseSubmitBehavior="true" />
<asp:Button ID="but_HiddenProxy" runat="server" Style="display: none" Text="Hidden Proxy Button for Modal Popup" ClientIDMode="Static" />
</td>
<td class="rt">
<asp:Button ID="but_AddTool" runat="server" AccessKey="A" CssClass="butGreen" Text="Add Tool" ToolTip="Add Tool - Alt A" />
</td>
</tr>
</table>
<asp:ModalPopupExtender ID="mpx_AddEditAccess" runat="server" CancelControlID="but_Cancel"
BehaviorID="pn_AddEditAccess" PopupControlID="pn_AddEditAccess" TargetControlID="but_HiddenProxy"
BackgroundCssClass="modalBackground" />
<asp:Panel ID="pn_AddEditAccess" runat="server" Width="500px" CssClass="modalPopup"
Style="display: block">
<div class="box">
<h2>
<asp:Label ID="lb_ModTitle" runat="server"></asp:Label>
</h2>
<asp:HiddenField ID="hd_AccessID" runat="server" ClientIDMode="Static"></asp:HiddenField>
<div class="block">
<asp:UpdatePanel ID="up_Access" runat="server" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl_ToolName" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<table>
<tr>
<th class="p66 rt">
Tool Name:
</th>
<td class="p66">
<asp:HiddenField ID="hd_ToolIDMod" runat="server" ClientIDMode="Static" />
<asp:DropDownList ID="ddl_ToolName" runat="server" AutoPostBack="true" AppendDataBoundItems="True"
DataSourceID="SqlDS_Tools" DataTextField="ToolName" DataValueField="ToolID" OnSelectedIndexChanged="ddl_ToolName_SIC">
<asp:ListItem Text="Please Select..." Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDS_Tools" runat="server" ConnectionString="<%$ ConnectionStrings:ToolsConnString %>"
SelectCommand="SELECT [ToolID], [ToolName] FROM [tbl_Tools] WHERE ([Redundant] = #Redundant)">
<SelectParameters>
<asp:Parameter DefaultValue="False" Name="Redundant" Type="Boolean" />
</SelectParameters>
</asp:SqlDataSource>
<asp:RequiredFieldValidator ID="rfv_ddl_ToolName" runat="server" ControlToValidate="ddl_ToolName"
CssClass="error" Display="Dynamic" ErrorMessage="Please Select Tool Name" InitialValue="0">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<th class="p66 rt">
Access Rights:
</th>
<td class="p66">
<asp:HiddenField ID="hd_AccessCodeMod" runat="server" ClientIDMode="Static" />
<asp:DropDownList ID="ddl_AccessCode" runat="server" Enabled="false">
<asp:ListItem Text="No Access" Value="0"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="p66">
<asp:Button ID="but_Cancel" runat="server" Text="Cancel" />
</td>
<td class="p66 rt">
<asp:Button ID="but_Save" runat="server" Text="Save" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</asp:Panel>
As you can see I have implemented two hidden buttons but_SetModalDetails and but_HiddenProxy. but_SetModalDetails has some codebehind which sets a couple of dropdown lists (one populated from a datasource, the other is populated dynamically based on the value of the first. The codebehind is...
Protected Sub but_SetModalDetails_Click(ByVal sender As Object, ByVal e As EventArgs) Handles but_SetModalDetails.Click
If hd_AccessID.Value = "0" Then
lb_ModTitle.Text = "Assigning Access Rights to:"
ddl_ToolName.SelectedIndex = 0
ddl_AccessCode.SelectedIndex = 0
ddl_AccessCode.Enabled = False
Else
lb_ModTitle.Text = "Edit Access Rights to:"
ddl_ToolName.SelectedValue = hd_ToolIDMod.Value
ddl_ToolName.Enabled = False
SqlStr = "SELECT AccessID AS ddlValue, AccessText as ddlText FROM tbl_AccessCodes WHERE ToolID = " & hd_ToolIDMod.Value
PopulateDDLvalue(ddl_AccessCode, SqlStr)
ddl_AccessCode.SelectedValue = hd_AccessCodeMod.Value
ddl_AccessCode.Enabled = True
End If
'NOW I NEED TO SIMULATE but_HiddenProxy Click
End Sub
As you can see at the end I need to simulate a click of but_HiddenProxy so that the modalPopup is shown populated with the correct data.
Any Ideas? Thanks
After all that... I was able to do everything in codebehind...
I only needed one hidden button but_HiddenProxy.
In the gridview instead of setting an onClick attribute for each edit image button I just set a commandname of 'AccessEdit' (don't use 'Edit'). I then had a method that handled the gridview.RowCommand event. This found the various info I needed by using findControl on the selected row. These values were then used to populate the dropdowns in the popup and then use the show command to make the popup visible.
One bit that did stump me for a while was why my RowCommand was not triggering when an imagebutton was clicked. I'd forgotten that I had validation in the modal which stopped the RowCommand being executed. I stuck a CausesValidation="false" in the imagebutton and all was OK.
Talk about using a hammer to crack a nut!

GridView isn't reflecting AJAX changes

I'm using AJAX right now to update my GridView when I search for a string of text in the gridview, or when I select from a dropdownlist what I want to order the Gridview by. This was working previously, but I had really messy code. So I've cleaned it up a little bit, added some parameters and such. Unfortunately, now, when the selectedindex of the dropdownlist is changed or when someone tries to search for a field, nothing happens - the page just refreshes. I'm also getting an exception saying "The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name".
If you need to see any more code then please let me know!
public vieworders()
{
this.PreInit += new EventHandler(vieworders_PreInit);
}
void vieworders_PreInit(object sender, EventArgs e)
{
orderByString = orderByList.SelectedItem.Value;
fieldString = searchTextBox.Text;
updateDatabase(fieldString, orderByString);
}
protected void updateDatabase(string _searchString, string _orderByString)
{
string updateCommand = "SELECT fName,lName,zip,email,cwaSource,price,length FROM SecureOrders WHERE fName LIKE #searchString OR lName LIKE #searchString OR zip LIKE #searchString OR email LIKE #searchString OR cwaSource LIKE #searchString OR length LIKE #searchString OR price LIKE #searchString ORDER BY #orderByString";
Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Cabot3");
ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];
// Create an SqlConnection to the database.
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
using (SqlCommand _fillDatabase = new SqlCommand(updateCommand, connection))
{
connection.Open();
_fillDatabase.Parameters.Add("#searchString", SqlDbType.VarChar, 50).Value = _searchString;
_fillDatabase.Parameters.Add("#orderByString", SqlDbType.VarChar, 50).Value = _orderByString;
_fillDatabase.ExecuteNonQuery();
dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);
// create the DataSet
dataSet = new DataSet();
// fill the DataSet using our DataAdapter
dataAdapter.Fill(dataSet, "SecureOrders");
DataView source = new DataView(dataSet.Tables[0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();
connection.Close();
}
}
Form
<form id="form1" runat="server">
<asp:ScriptManager ID = "ScriptManager" runat="server" />
<div>
<asp:Label runat="server" id = "orderByLabel" Text = "Order By: " />
<asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
<asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
<asp:ListItem Value="lName">Last Name</asp:ListItem>
<asp:ListItem Value="state">State</asp:ListItem>
<asp:ListItem Value="zip">Zip Code</asp:ListItem>
<asp:ListItem Value="cwaSource">Source</asp:ListItem>
<asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label runat="server" ID="searchLabel" Text="Search For: " />
<asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
<asp:Button ID="searchButton" runat="server" Text="Search" />
</div>
<div>
<asp:UpdatePanel ID = "up" runat="server">
<ContentTemplate>
<div style= "overflow:auto; height:50%; width:100%">
<asp:GridView ID="DefaultGrid" runat = "server" DataKeyNames = "IdentityColumn"
onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
autogenerateselectbutton = "true">
<SelectedRowStyle BackColor="Azure"
forecolor="Black"
font-bold="true" />
<Columns>
<asp:TemplateField HeaderText="Processed">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" AutoPostBack = "true" Checked ='<%#Eval("processed") %>' OnCheckedChanged="CheckBoxProcess_CheckedChanged" runat="server" Enabled="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
<div style= "overflow:auto; height:50%; width:100%" />
<table border="1">
<tr>
<td>Name: </td>
<td><%=name %></td>
</tr>
<tr>
<td>Zip: </td>
<td><%=zip %></td>
</tr>
<tr>
<td>Email: </td>
<td><%=email %></td>
</tr>
<tr>
<td>Length: </td>
<td><%=length %></td>
</tr>
<tr>
<td>Price: </td>
<td><%=price %></td>
</tr>
<tr>
<td>Source: </td>
<td><%=source %></td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I have never used the UpdatePanel since my company uses Telerik, but from the examples I see during my research I remember seeing a trigger component.
From my understanding, if the control is w/i the UpdatePanel itself, then you do not have to specify the trigger, since it is assumed.
For your scenario, the trigger (dropdownlist) is outside of the UpdatePanel. You may need to include this in your aspx:
<asp:UpdatePanel ID = "up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="orderByList" >
</Triggers>
<ContentTemplate>
...
Try the following:
In HTML move the update panel direct after the scriptmanager line.
Move the code lines in vieworders_PreInit to vieworders_PageLoad with !IsPostPack clause.

Custom Paging in Child (Inner) Nested Repeaters

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

Resources