VB Gridview Populating and Sorting - vb.net

I am having a problem getting my GridView's DataSource worked out. I have tried multiple variations in coding, each with their own issues. I have the DataSourceID defined using the GridView Configuration manager. When I attempt to call my stored procedure to populate my GridView, I get no results. So, I tried to define a DataSource in the codebehind and manually bind (and set DataSourceID = '' to avoid error). That populates my GridView very well, but won't allow for sorting.
Here's my question: Does anyone see what I am doing wrong so that neither of these solutions works? I've repurposed code from another project I did, and they are identical (in other project, both DataSourceID and Datasource are used with no error?) Here's my ASP.net Gridview and Proc code:
<asp:GridView ID="gvUserSearch" runat="server" style="z-index: 1; left: 56px; top: 382px; position: absolute; height: 133px; width: 187px" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="UserSearchDataSource" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical">
<AlternatingRowStyle BackColor="Gainsboro" />
<Columns>
<asp:CommandField ShowSelectButton="True" >
<ItemStyle ForeColor="#0066FF" />
</asp:CommandField>
<asp:BoundField DataField="SubscriberID" HeaderText="SubscriberID" SortExpression="SubscriberID" Visible="False" />
<asp:BoundField DataField="Last Name" HeaderText="Last Name" SortExpression="Last Name" >
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="First Name" HeaderText="First Name" SortExpression="First Name" >
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="EmailAddress" HeaderText="Email Address" SortExpression="EmailAddress" >
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="locationid" HeaderText="Unit ID" SortExpression="locationid" >
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Center" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="unit_name" HeaderText="Unit Name" SortExpression="unit_name" >
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="Birthday" HeaderText="Birthday" ReadOnly="True" SortExpression="Birthday" DataFormatString="{0:MMMM/DD/yyyy}" HtmlEncode="False" HtmlEncodeFormatString="False" >
<ItemStyle HorizontalAlign="Center" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="Zip Code" HeaderText="Zip Code" SortExpression="Zip Code" >
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Center" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="Status" HeaderText="Status" ReadOnly="True" SortExpression="Status" >
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Left" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="DateUnsubscribed" HeaderText="Unsubscribe Date" ReadOnly="True" SortExpression="DateUnsubscribed" DataFormatString="{0:MMMM/DD/yyyy}" HtmlEncode="False" >
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Center" Wrap="False" />
</asp:BoundField>
</Columns>
<asp:SqlDataSource ID="UserSearchDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:CafeWorksConnectionString %>" SelectCommand="MarketingPortal_UserSearchProc" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="txtEmail" Name="Email" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="txtLastName" Name="LastName" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="txtFirstName" Name="FirstName" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Here is my VB.net codebehind:
Dim CafeWorksConnection As New SqlConnection()
Dim CafeWorksCS As String
Dim CafeWorksDA As SqlDataAdapter
Dim CafeWorksCB As SqlCommandBuilder
Dim CafeWorksDS As New DataSet
Dim CafeWorksSqlC As New SqlCommand
Dim CafeWorksReader As SqlDataReader
Private Sub DBConnect()
'Get the connection string from the web.config file
CafeWorksCS = ConfigurationManager.ConnectionStrings("CafeWorksConnectionString").ConnectionString
'Assign the Connection String to the Connection
CafeWorksConnection.ConnectionString = CafeWorksCS
'Open the database connection
CafeWorksConnection.Open()
End Sub
Private Sub Populate_GridView()
'Make a database connection
DBConnect()
'Define the type of query being executed (Stored Procedure)
CafeWorksSqlC.CommandType = CommandType.StoredProcedure
CafeWorksSqlC.CommandText = "MarketingPortal_UserSearchProc "
'Define the stored procedure parameters
CafeWorksSqlC.Parameters.AddWithValue("#Email", txtEmail.Text)
CafeWorksSqlC.Parameters.AddWithValue("#LastName", txtLastName.Text)
CafeWorksSqlC.Parameters.AddWithValue("#FirstName", txtFirstName.Text)
'Make a connection for the stored procedure to run
CafeWorksSqlC.Connection = CafeWorksConnection
'CafeWorksConnection.Open()
'Executes the stored procedure and stores the result set
CafeWorksReader = CafeWorksSqlC.ExecuteReader()
'You need to bind the data to the GridView
'Got error that DataSourceID and DataSource can't be defined (DataSourceID define in Gridview ASP.net
'code and is not giving me a result set for some reason, so I added the DataSource and DataBind
'gvUserSearch.DataSourceID = ""
gvUserSearch.DataSource = CafeWorksDS
gvUserSearch.DataBind()
'Always close the database connection when you are finished
CafeWorksConnection.Close()
End Sub
Protected Sub btnNameSearch_Click(sender As Object, e As EventArgs) Handles btnNameSearch.Click
'Call the Sub Populate_GridView to display results of search
Populate_GridView()
'Clear out the text boxes - Keeps data from lingering into other searches
txtEmail.Text = ""
txtLastName.Text = ""
txtFirstName.Text = ""
End Sub
I'm still relatively new to this, and my code may not be pretty. I would appreciate any help that anyone could give me. Thank you!

Well your first issue is that you do not have an onsorting attribute of your GridView defined, like this:
onsorting="gvUserSearch_Sorting"
This represents an event handler for whenever a sort operation is needed, such as the user clicking on the header of a column to sort it.
I recommend that you change your DataSource type to DataTable, because the DataTable data structure lends itself to having a view built against it, which you will see later is how we can easily apply the sort direction and the sort expression for the column. Here is a utility function that can return a DataTable to be used by your DataSource property:
Private Function GetGridViewDataSource() As DataTable
Dim dtGrid As New DataTable()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
' Change this to either execute the SQL you want or change the command object to execute a stored procedure
Dim strSelect As String = "SELECT FirstName,LastName,Location FROM Details"
Dim cmd As New SqlCommand(strSelect, con)
Dim dAdapter As New SqlDataAdapter(cmd)
dAdapter.Fill(dtGrid)
Return dtGrid
End Function
Note: You would need to change your DataSource assignment to call this function, like this: gvUserSearch.DataSource = GetGridViewDataSource()
Now that we have the source as a DataTable, we can start to manage the sorting, specifically keeping track of sort direction (ascending or descending) via a class property, like this:
Public Property dir() As SortDirection
Get
If ViewState("dirState") Is Nothing Then
ViewState("dirState") = SortDirection.Ascending
End If
Return DirectCast(ViewState("dirState"), SortDirection)
End Get
Set
ViewState("dirState") = value
End Set
End Property
Now we are finally ready to implement the actual sorting handler, like this:
Protected Sub gvDetails_Sorting(sender As Object, e As GridViewSortEventArgs)
Dim sortingDirection As String = String.Empty
If dir = SortDirection.Ascending Then
dir = SortDirection.Descending
sortingDirection = "Desc"
Else
dir = SortDirection.Ascending
sortingDirection = "Asc"
End If
Dim sortedView As New DataView(GetGridViewDataSource())
sortedView.Sort = Convert.ToString(e.SortExpression) & " " & sortingDirection
gvDetails.DataSource = sortedView
gvDetails.DataBind()
End Sub
Note: What this method does is to ask the ViewState what the sorting direction is and then creates a DataView from the DataTable and applies the sorting expression, defined in the grid view column, and the sorting direction to rebind the data source to grid.

Related

GridCommandEventArgs items have no data values

I have a RadGrid with which I need to add, update, and delete data. I've gotten the functionality to work, but I also need to do some checking on the data before it gets added/updated, including setting a field based on other data. I also want to log what was done.
My Insert functionality is working. The RadGrid is as follows:
<telerik:RadGrid ID="CarrierRadGrid" runat="server" AllowFilteringByColumn="True" AllowPaging="False" Width="100%" Height="800px" PageSize="20" da
AllowSorting="True" DataSourceID="CarrierData" ShowStatusBar="True"
OnInsertCommand="CarrierRadGrid_InsertCommand" OnItemInserted="CarrierRadGrid_ItemInserted" AllowAutomaticInserts="true"
OnUpdateCommand="CarrierRadGrid_UpdateCommand" OnItemUpdated="CarrierRadGrid_ItemUpdated" AllowAutomaticUpdates="true"
OnDeleteCommand="CarrierRadGrid_DeleteCommand" OnItemDeleted="CarrierRadGrid_ItemDeleted" AllowAutomaticDeletes="true"
Skin="Telerik" AutoGenerateColumns="False" AutoGenerateEditColumn="false" AutoGenerateDeleteColumn="false">
<ClientSettings EnableRowHoverStyle="true" EnablePostBackOnRowClick="false">
<Scrolling AllowScroll="true" UseStaticHeaders="true" SaveScrollPosition="true" FrozenColumnsCount="5" />
<Selecting AllowRowSelect="true" />
<Resizing AllowColumnResize="true" AllowResizeToFit="true" />
<ClientEvents OnRowDeleting="void 0" />
</ClientSettings>
<GroupingSettings CaseSensitive="false" />
<ExportSettings HideStructureColumns="true">
</ExportSettings>
<HeaderContextMenu EnableAutoScroll="False">
</HeaderContextMenu>
<MasterTableView DataKeyNames="CarrierScacID" DataSourceID="CarrierData" AllowAutomaticInserts="true" AllowAutomaticDeletes="True" AllowAutomaticUpdates="true"
CommandItemDisplay="Top" HierarchyLoadMode="ServerOnDemand" EditMode="InPlace">
<CommandItemSettings
ShowExportToWordButton="false"
ShowExportToCsvButton="false"
ShowExportToPdfButton="false"
ShowAddNewRecordButton="true">
</CommandItemSettings>
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" CancelText="Cancel" EditText="Edit" InsertText="Add"
UpdateText="Update" HeaderStyle-Width="30px" UniqueName="CarrierEditButton" />
<telerik:GridClientDeleteColumn ButtonType="ImageButton" Text="Delete" HeaderStyle-Width="30px" UniqueName="CarrierDeleteButton"
ConfirmTextFields="CarrierScac" ConfirmTextFormatString="Are you sure you want to delete carrier {0}?" CommandName="Delete" />
<telerik:GridBoundColumn DataField="CarrierScacID" HeaderText="CarrierScacID" UniqueName="CarrierScacID" ReadOnly="True" Display="false" />
<telerik:GridTemplateColumn>
<EditItemTemplate>
<telerik:RadLabel runat="server" ID="CarrierScac" Text='<% #Bind("CarrierScac") %>' ViewStateMode="Disabled" Enabled="false" />
</EditItemTemplate>
<InsertItemTemplate>
<telerik:RadTextBox ID="CarrierScac" runat="server" Text='<% #Bind("CarrierScac") %>' />
</InsertItemTemplate>
<ItemTemplate>
<telerik:RadLabel runat="server" ID="CarrierScac" Text='<% #Bind("CarrierScac") %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="CarrierScac" HeaderText="SCAC" UniqueName="CarrierScac" FilterControlWidth="40px" HeaderStyle-Width="75px" />
<telerik:GridBoundColumn DataField="CarrierName" HeaderText="Carrier Name" UniqueName="CarrierName" ItemStyle-Wrap="false"
HeaderStyle-Width="200px" FilterControlWidth="160px" FilterControlAltText="Filter by Carrier Name" SortExpression="CarrierName" />
<telerik:GridBoundColumn DataField="Address" HeaderText="Address" UniqueName="Address" ItemStyle-Wrap="false"
HeaderStyle-Width="200px" FilterControlWidth="160px" FilterControlAltText="Filter by Address" SortExpression="Address" />
<telerik:GridBoundColumn DataField="City" HeaderText="City" UniqueName="City" HeaderStyle-Width="100px" />
<telerik:GridBoundColumn DataField="State" HeaderText="State" UniqueName="State" FilterControlWidth="30px" HeaderStyle-Width="65px" />
<telerik:GridBoundColumn DataField="ZIP" HeaderText="ZIP" UniqueName="ZIP" FilterControlWidth="55px" HeaderStyle-Width="90px" />
<telerik:GridBoundColumn DataField="Country" HeaderText="Country" UniqueName="Country" FilterControlWidth="55px" HeaderStyle-Width="90px" />
<telerik:GridBoundColumn DataField="Contact" HeaderText="Contact" UniqueName="Contact" ItemStyle-Wrap="false" HeaderStyle-Width="110px" />
<telerik:GridBoundColumn DataField="Phone" HeaderText="Phone" UniqueName="Phone" ItemStyle-Wrap="false" HeaderStyle-Width="115px" />
<telerik:GridBoundColumn DataField="Fax" HeaderText="Fax" UniqueName="Fax" ItemStyle-Wrap="false" HeaderStyle-Width="115px" />
<telerik:GridBoundColumn DataField="User" HeaderText="User" UniqueName="User" HeaderStyle-Width="120px" ReadOnly="true" />
<telerik:GridBoundColumn DataField="Update" HeaderText="Update" UniqueName="Update" ItemStyle-Wrap="false" HeaderStyle-Width="230px" ReadOnly="true" />
<telerik:GridBoundColumn DataField="Comments" HeaderText="Comments" UniqueName="Comments" ItemStyle-Wrap="false" HeaderStyle-Width="230px" ReadOnly="true" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
In code-behind, I have the following:
Protected Sub CarrierRadGrid_InsertCommand(sender As Object, e As GridCommandEventArgs)
e = SetCommentsField(e)
End Sub
Protected Sub CarrierRadGrid_ItemInserted(sender As Object, e As GridInsertedEventArgs)
Dim msg As String = String.Format("New carrier (Carrier Code: {0}) added to the database.", e.Item.Cells(6).Text)
Log(msg)
MessageBox(msg)
End Sub
Private Shared Function SetCommentsField(e As GridCommandEventArgs) As GridCommandEventArgs
If String.IsNullOrEmpty(e.Item.Cells(18).Text) Then
Dim update As String = e.Item.Cells(17).Text
If Not String.IsNullOrEmpty(update) Then
e.Item.Cells(18).Text = String.Format("Modified by {0}", update)
End If
End If
Return e
End Function
But when debugging, I find all of the e.Item.Cells Text properties are " ". Yet the record added to the database has the data I put into the fields, as it should.
What could be missing? Or extra?
EDIT: Including the whole RadGrid, instead of only the part I thought was relevant.
Below are two options to access the cell data.
This accesses the newly inserted data using a hashtable/dictionary. It only retrieves data from EditItems so read-only rows are not included
This converts your editItem to a data item and accesses the current cell which you will find is consistently because the data has not been put there yet. THe data entered only exists in the edit items.
Protected Sub CarrierRadGrid_InsertCommand(sender As Object, e As GridCommandEventArgs)
'1
Dim insertValues As New Hashtable()
CType(e.Item, GridEditableItem).ExtractValues(insertValues)
Dim dd = insertValues("CarrierScac")
'2
Dim item As GridDataItem = CType(e.Item, GridDataItem)
Dim itemD = item("CarrierScac").Text
e = SetCommentsField(e)
End Sub
The above should get you what you need I suspect, however to add some color
Telerik uses to denote an empty/null cell text field which makes sense here because the cell text you are trying to grab does not exist. It IS empty and you ARE accessing it. The fields you are accessing, however, are read only and there does not appear to be a default value. Are you setting that elsewhere? I've included a function below that checks for String.IsNullOrEmpty and that we use frequently to spare some logic. I'd put it in a safe place and consume it as needed because empty cells in a radgrid will never actually be string.empty.
Public Function RadGridCellIsNullOrEmpty(value As String) As Boolean
value = value.Trim()
Return (String.IsNullOrEmpty(value) OrElse String.IsNullOrWhiteSpace(value) OrElse value.Contains(" "))
End Function
Private Shared Function SetCommentsField(byRef e As GridCommandEventArgs) As GridCommandEventArgs
If RadGridCellIsNullOrEmpty(e.Item.Cells(18).Text) Then
Dim update As String = e.Item.Cells(17).Text
If Not RadGridCellIsNullOrEmpty(update) Then
e.Item.Cells(18).Text = String.Format("Modified by {0}", update)
End If
End If
Return e
End Function

index Gridview Attribute onclic with button hidden

I need select row in gridview with a button hidden, but without postback because i need that stay on position clicked in gridview, this step i got it, but when i clicked on row capture index = 0, but when i click in button (no hidden in this time), capture correct index, how can I do this, thanks for your help or any idea.
my code is:
aspx:
<asp:UpdatePanel ID="UPGrvConfident" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="table-responsive" id="gridDentalNetworkContainer" style="overflow: auto; height: 207px; cursor: pointer; padding: 0px">
<asp:GridView ID="gridDentalNetwork" EnableViewState="true" AllowSorting="false" runat="server" GridLines="None" Width="100%"
EmptyDataText="No hay elementos a mostrar." AutoGenerateColumns="false" ClientIDMode="Static"
DataKeyNames="numero" ShowHeaderWhenEmpty="true" HeaderStyle-HorizontalAlign="Center" HeaderStyle-BackColor="Gainsboro" HeaderStyle-BorderWidth="2px" RowStyle-BackColor="White"
RowStyle-BorderColor="White" RowStyle-Font-Size="Smaller" RowStyle-Font-Bold="false" CellPadding="3" CellSpacing="0">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" CommandName="Delete" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Numero" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="Nombre" HeaderText="Nombre" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="Identificacion" HeaderText="Identificación" ItemStyle-Width="10%" HeaderStyle-Width="10%" />
<asp:BoundField DataField="Msg" HeaderText="Nombre">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="ApellidoPaterno" HeaderText="Primer Apellido" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="ApellidoMaterno" HeaderText="Segundo Apellido" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="Contrato" HeaderText="Contrato" />
<asp:BoundField DataField="contratocanal" HeaderText="Contratante" ItemStyle-Width="242px" HeaderStyle-Width="242px">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Titular" HeaderText="Usuario Principal">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="NroDoc" HeaderText="nro_row" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="NroPariente" HeaderText="nro_pariente" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="NroPol" HeaderText="nro_pol" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" HeaderStyle-Width="5px" />
<asp:BoundField DataField="NroAseg" HeaderText="nro_aseg" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="TxtRed" HeaderText="fec_nac" ItemStyle-CssClass="Hides" HeaderStyle-CssClass="Hides" />
<asp:BoundField DataField="Plan" HeaderText="Plan">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="fec_alta" HeaderText="Fecha Ingreso" ItemStyle-Width="96px" HeaderStyle-Width="96px">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
<AlternatingRowStyle BackColor="#f2f2f2" />
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
aspx.vb (code behind)
RowdataBound
Protected Sub gridDentalNetwork_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles gridDentalNetwork.RowDataBound
'e.Row.Cells(0).Style("display") = "none"
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes("onmouseover") = "this.style.cursor='hand';this.style.textDecoration='underline';"
e.Row.Attributes("onmouseout") = "this.style.textDecoration='none';"
Dim btnSelect As Button = TryCast(e.Row.FindControl("btnSelect"), Button)
btnSelect.CommandArgument = e.Row.RowIndex.ToString()
'e.Row.Attributes("onclick") = String.Format("document.getElementById('{0}').click();", btnSelect.ClientID)
e.Row.Attributes.Add("onclick", "document.getElementById('" & btnSelect.ClientID & "').value = '" & e.Row.RowIndex.ToString() & "'; alert(document.getElementById('" & btnSelect.ClientID & "').value); darClick();")
'e.Row.Attributes.Add("onclick", "var dato = document.getElementById('btnSelect').value; '<%Session['temp']='+ dato +';%>'; alert('<%=Session['temp']%>');")
'e.Row.Attributes("onclick") = String.Format("document.getElementById('{0}').click();", btnSelect.ClientID)
'e.Row.Attributes("onclick") = Page.ClientScript.GetPostBackClientHyperlink(gridDentalNetwork, "Select$" + e.Row.RowIndex.ToString())
'e.Row.Attributes.Add("onclick", String.Format("document.getElementById('{0}').click();", btnSelect.ClientID))
e.Row.ToolTip = "Clic para seleccionar"
End If
End Sub
Method: I am using RowDeleting for commandField.
Protected Sub gridDentalNetwork_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs) Handles gridDentalNetwork.RowDeleting
Dim ListBiored As List(Of MClienteSimple) = New List(Of MClienteSimple)
Dim grvfila As GridViewRow
Dim indexx As String = Session("index")
grvfila = gridDentalNetwork.Rows(e.RowIndex)
Dim lstClientesConf As New MClienteDentalNetwork
lstClientesConf = DirectCast(Session("ClientesConf"), List(Of MClienteDentalNetwork))(grvfila.DataItemIndex)
...etc..etc
End Sub

showing/hiding a row in the master-detail grid depending on selection of drop down list TELERIK

Required system: i'm trying to create a master detail grid in telerik where if the user changes his/her selection on a drop down list in the master grid, the row underneath his/her current row in the details grid appears, and if his/her selection changes again it would disappear.
background information: this system was designed to allow the end user (petrol station auditor) to inspect petrol station, and if he/she happens to find a violation he/she would immediately identify what action should be taken.i've decided to create a checklist with a drop down menu where if the user finds a violation he/she would change the drop down list appears and the procedure that has to be performed due to the violation is shown.
problem: i'm trying to create an event using selectedindexchanged in the master grid depending on the drop down list selection. if the dropdown list selection is "in violation" the row would appear in the details grid, otherwise it would disappear. the value i'm using to map the master-details rows to each other is called "SRS".
when trying to obtain the row index with variable "rowIndex", i find an error regarding a type change from one type to another performing my typecasting. i've tried rigorously to solve the issue with no results.
i would be very grateful if someone could provide the code to resolve my issue
NOTE: i will highlight the problematic line of code
vb code (problematic code):
Protected Sub SqlDataSource_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource.Selecting
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
**PROBLEMATIC LINE** ------------------------> Dim rowIndex As Integer = CType(CType(sender, RadDropDownList).Parent.Parent, GridViewRow).RowIndex
Dim SRSText As String = RadGrid1.MasterTableView.Items(rowIndex).Cells(3).Text
If sender.SelectedValue = "in violation" Then
SqlDataSource1.SelectParameters.Add(":SRSText", SRSText)
RadGrid1.MasterTableView.DetailTables(0).DataSource = SqlDataSource1
RadGrid1.MasterTableView.DetailTables(0).DataBind()
Else
End If
End Sub
End Class
accompanying ASPX code, for further information:
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"
CodeFile="Default.aspx.vb" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js">
</asp:ScriptReference>
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js">
</asp:ScriptReference>
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js">
</asp:ScriptReference>
</Scripts>
</telerik:RadScriptManager>
<telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server">
</telerik:RadStyleSheetManager>
<telerik:RadTextBox ID="RadTextBox1" runat="server" AutoPostBack="True" LabelWidth="64px"
Resize="None" Text="please enter the PFS number" Width="160px">
</telerik:RadTextBox>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
</telerik:RadAjaxManager>
<asp:SqlDataSource ID="SqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT * FROM "CHECKLIST"">
</asp:SqlDataSource>
<p>
</p>
<telerik:RadGrid ID="RadGrid1" runat="server" CellSpacing="0" DataSourceID="SqlDataSource"
GridLines="None" AllowMultiRowSelection="True" AutoGenerateColumns="False">
<ExportSettings>
<Pdf>
<PageHeader>
<LeftCell Text=""></LeftCell>
<MiddleCell Text=""></MiddleCell>
<RightCell Text=""></RightCell>
</PageHeader>
<PageFooter>
<LeftCell Text=""></LeftCell>
<MiddleCell Text=""></MiddleCell>
<RightCell Text=""></RightCell>
</PageFooter>
</Pdf>
</ExportSettings>
<ClientSettings EnablePostBackOnRowClick="True" EnableRowHoverStyle="True">
<Selecting AllowRowSelect="True" />
</ClientSettings>
<MasterTableView DataKeyNames="INSPECTIONNO" DataSourceID="SqlDataSource">
<CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
<RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>
<ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
<HeaderStyle Width="20px"></HeaderStyle>
</ExpandCollapseColumn>
<DetailTables>
<telerik:GridTableView AutoGenerateColumns="false" DataSourceID="SqlDataSource1"
Width="100%">
<CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
<ParentTableRelation>
<telerik:GridRelationFields DetailKeyField="SRS" MasterKeyField="SRS"></telerik:GridRelationFields>
</ParentTableRelation>
<RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column"></RowIndicatorColumn>
<ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column"></ExpandCollapseColumn>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
</EditFormSettings>
<BatchEditingSettings EditType="Cell"></BatchEditingSettings>
<PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
</telerik:GridTableView> </DetailTables>
<Columns>
<telerik:GridBoundColumn DataField="PFSNO" DataType="System.Decimal" FilterControlAltText="Filter PFSNO column"
HeaderText="PFSNO" SortExpression="PFSNO" UniqueName="PFSNO">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="INSPECTIONNO" DataType="System.Decimal" FilterControlAltText="Filter INSPECTIONNO column"
HeaderText="INSPECTIONNO" ReadOnly="True" SortExpression="INSPECTIONNO" UniqueName="INSPECTIONNO">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="INPECTIONDATENTIME" FilterControlAltText="Filter INPECTIONDATENTIME column"
HeaderText="INPECTIONDATENTIME" SortExpression="INPECTIONDATENTIME" UniqueName="INPECTIONDATENTIME">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="SRS" DataType="System.Decimal" FilterControlAltText="Filter SRS column"
HeaderText="SRS" SortExpression="SRS" UniqueName="SRS">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="VIOLATIONTYPE" FilterControlAltText="Filter VIOLATIONTYPE column"
HeaderText="VIOLATIONTYPE" SortExpression="VIOLATIONTYPE" UniqueName="VIOLATIONTYPE">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="VIOLATIONDESCRIPTION" FilterControlAltText="Filter VIOLATIONDESCRIPTION column"
HeaderText="VIOLATIONDESCRIPTION" SortExpression="VIOLATIONDESCRIPTION" UniqueName="VIOLATIONDESCRIPTION">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="REMARKS" FilterControlAltText="Filter REMARKS column"
HeaderText="REMARKS" SortExpression="REMARKS" UniqueName="REMARKS">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="ITEM" FilterControlAltText="Filter ITEM column"
HeaderText="ITEM" SortExpression="ITEM" UniqueName="ITEM">
</telerik:GridBoundColumn>
<telerik:GridAttachmentColumn FileName="attachment"
FilterControlAltText="Filter column column" HeaderText="audit status-"
UniqueName="column">
</telerik:GridAttachmentColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<telerik:RadDropDownList ID="violDrop" runat="server" DataSourceID="dd2_SqlDataSource1" DataTextField="LISTITEM" DataValueField="LISTITEM" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true"/>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column">
</EditColumn>
</EditFormSettings>
<BatchEditingSettings EditType="Cell"></BatchEditingSettings>
<PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
</MasterTableView>
<PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
<FilterMenu EnableImageSprites="False">
</FilterMenu>
</telerik:RadGrid>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT * FROM "MEMO" WHERE ("SRS" = :SRS)">
<SelectParameters>
<asp:ControlParameter ControlID="RadGrid1" Name="SRS" PropertyName="SelectedValue"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="dd2_SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT "LISTITEM" FROM "DROPDOWNLIST"">
</asp:SqlDataSource>
</asp:Content>
Please try with the below code snippet.
Let me know if any concern.
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim item As GridDataItem = TryCast(TryCast(sender, DropDownList).NamingContainer, GridDataItem)
Dim index As Integer = item.ItemIndex
'Access current row index here
End Sub
First of all thanks for the reply
Unfortunately, the code snippet that you have provided didn't work for my case, it gave me an error message stating "object reference was not set to an instance of an object"
Note:I copied and pasted the code changing the name iof the index variable

Loop through gridview getting error

I have a gridview that I am trying to loop through to get the values to update and store in my database. Gridview code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False"
Width="1020px" EnableTheming="True" PageSize="25" CellPadding="4"
ForeColor="#333333" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Column1" HeaderText="Col1" ReadOnly="True" >
<ItemStyle Width="35px" />
</asp:BoundField>
<asp:BoundField DataField="Column2" HeaderText="Col2" />
<asp:BoundField DataField="Column3" HeaderText="Col3" />
<asp:BoundField DataField="Column4" HeaderText="Col4" />
<asp:BoundField DataField="Column5" HeaderText="Col5" />
<asp:TemplateField HeaderText="Col6">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Column6") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text="$"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Column6", "{0:f}") %>' CssClass="boxright"></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:BoundField DataField="Column7" ReadOnly="True" >
<ItemStyle Width="35px" />
</asp:BoundField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
<PagerSettings Mode="NextPreviousFirstLast" />
<PagerStyle BackColor="#003399" ForeColor="White" HorizontalAlign="Left" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
I am using a button click event to trigger the stored sql procedure to update my table as follows...
Protected Sub btnB_Save_Click(sender As Object, e As EventArgs) Handles btnB_Save.Click
Dim gvRow As GridViewRow
Dim str As String = ""
For Each gvRow As GridViewRow In gv_Budgets.Rows
str = ((str + gvRow.Cells(0).Text) + (gvRow.Cells(1).Text) + (gvRow.Cells(2).Text) + (gvRow.Cells(3).Text) + (gvRow.Cells(4).Text) + (gvRow.Cells(6).Text))
Dim dtRow As TextBox = CType(gvRow.FindControl("TextBox1"), TextBox)
Response.Write(dtRow.Text)
dt = dal.ExecuteStoredProc(DAL.dbType.SqlServer, "UpdateData", "#col1", str + gvRow.Cells(0).Text, "#col2", str + gvRow.Cells(1).Text, "#col3", str + gvRow.Cells(2).Text, "#col4", str + gvRow.Cells(3).Text, "#col5", str + gvRow.Cells(4).Text, "#col6", dtRow.Text, "#col7", str + gvRow.Cells(6).Text, "#txt1", Textbox2.Text, "#txt2", Textbox3.Text)
Next
End Sub
However, I keep getting those blue syntax error lines under my "dt(datatable)" expression... Any ideas on how or why this is doing this?
Well the "Variable gvRow hides..." error is happening because you've declared gvRow outside the loop and then redeclared it in the definition of the loop.
Dim gvRow As GridViewRow ' First declaration
Dim str As String = ""
For Each gvRow As GridViewRow In gv_Budgets.Rows ' Skip the "As GridViewRow here
The other error is coming from your expression:
dt = dal.ExecuteStoredProc( ...
I'm assuming (because you don't have it listed) that dt is some global variable of type DataTable somewhere. In this case it looks like your sProc is returning a string and attempting to insert it into a datatable object. Make sure your sProc returns a valid datatable. In the meantime you may try to insert the result into a string just to get things working until you can work that out.

vb.net datatype in manually added column

Dim pctofpax As New DataColumn
pctofpax = New DataColumn("PCTPAX1", GetType(Decimal))
pctofpax.Expression = "[ASOFPAX] / [YEPAX]"
ds.Tables("workplease").Columns.Add(pctofpax)
Dim avgppax As New DataColumn
avgppax = New DataColumn("AVG PAX", GetType(Double))
avgppax.Expression = "[Current Sales] / [Current PAX]"
ds.Tables("workplease").Columns.Add(avgppax)
These are two columns that i added into my asp.net/vb.net datagrid. the problem is i keep trying to change the datatypes so they show up as numbers with only two decimals but it is not working
<span lang="en-us">Sales As Of Analysis</span><br />
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Vertical">
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#DCDCDC" />
</asp:GridView>
<asp:BoundColumn DataField="PCTPAX1"
HeaderText="PCTPAX1"
DataFormatString="{0:c}">
</div>
</form>
</body>
</html>
and nothing happend to my data
If it's just a matter of displaying only two decimals, this can be accomplished in the display code for the DataGrid:
<asp:BoundField DataField="PCTPAX1"
HeaderText="PCTPAX1"
DataFormatString="{0:c}">
Note the DataFormatString value of {0:c} which specifies that the formatting of the value in that field should be "currency." (You can also try with a capital C, I don't have a test handy for it right now.) There's a lot more you can do with format strings, more information here.
Or do you want the actual values to be rounded to currency values? You'll likely use Math.Round for that, though I don't have an example handy. There's information about that here.
Edit: Based on your comment(s), it sounds like you were attempting to change data types at the database level. This won't really impact the code. The value coming back from the database in the form of a double or decimal or some other numeric likely won't carry that precision back to the code. As far as the DataGrid is concerned, it's calling .ToString() on a double and showing the result. No database data type is involved. Using the DataFormatString property to pass a format string to the .ToString() method is how to change the display.
Edit again based on your question edit: Your HTML is broken. You have the BoundColumn outside of the grid, and the column tag itself isn't closed. Columns go inside the grid. See the grid layout here. Basically, you'd want something more like:
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Vertical">
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="PCTPAX1"
HeaderText="PCTPAX1"
DataFormatString="{0:c}">
</asp:BoundField>
</Columns>
</asp:GridView>
Changing the type of a column which is already in your datatable doesn't work. or at least not that i know. if you just want to get a different formatting, look at the answers above.