I have this gridview inside an updatepanel:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" ForeColor="Black"
GridLines="Horizontal" Height="100%" Width="100%" HorizontalAlign="Justify" CssClass="table-responsive-lg table-striped table-hover" CellPadding="5" Style="text-align: center" OnRowEditing="GridView1_RowEditing">
This edit button on the row:
<ItemTemplate>
<asp:LinkButton ID="btnSelect" runat="server" CausesValidation="False" CommandName="Edit"
ToolTip="Seleziona"><i class="far fa-hand-point-up fa-3x" aria-hidden="true"></i></asp:LinkButton>
</ItemTemplate>
And this dropdown inside an EditItemTemplate:
<asp:TemplateField HeaderText="Mittente" SortExpression="Mittente">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#: Bind("Mittente") %>' CssClass="content"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<div style="text-align: left">
<div class="wrapper">
<asp:Button ID="btnPrendiMail" runat="server" Text="Prendi" OnClick="btnPrendiMail_Click" CssClass="btn btn-default" />
<asp:SqlDataSource ID="sqlClienti" runat="server"
ConnectionString="<%$ ConnectionStrings:dbVulcanoConnectionString %>"
SelectCommand="select idcliente,RagSociale,concat(ragsociale,' [' ,idcliente, ']') as Descr from clienti order by RagSociale"></asp:SqlDataSource>
<asp:DropDownList ClientIDMode="Static" OnSelectedIndexChanged="ddlClienti_SelectedIndexChanged" ID="ddlClienti" runat="server" Font-Size="X-Large" Font-Bold="True" AutoPostBack="true" DataSourceID="sqlClienti" DataTextField="Descr" DataValueField="idCliente" AppendDataBoundItems="true" CssClass="select2-single form-control-div" >
<asp:ListItem Text="-- Cerca Cliente per ID o Ragione Sociale --" Value="0" Selected="True"></asp:ListItem>
</asp:DropDownList>
</div>
<asp:Label ID="lblEmailMittente" ClientIDMode="Static" runat="server" Text='<%#: Bind("Mittente") %>' CssClass="content"
Visible="false"></asp:Label>
</div>
</EditItemTemplate>
<ItemStyle Width="10%" />
</asp:TemplateField>
I would to change the selected value of the dropdown when the Edit button is pressed, executing this subroutine on RowEditing event of the gridview:
Protected Sub GridView1_RowEditing(sender As Object, e As GridViewEditEventArgs)
Dim gvRow As GridViewRow = GridView1.Rows.Item(e.NewEditIndex())
Dim ddlClienti As DropDownList = TryCast(gvRow.FindControl("ddlClienti"), DropDownList)
Dim lblEmailMittente As Label = TryCast(gvRow.FindControl("lblEmailMittente"), Label)
If dbVulcano.emails.Any(Function(m) m.email = lblEmailMittente.Text) Then
Dim email As emails = dbVulcano.emails.Where(Function(m) m.email = lblEmailMittente.Text).SingleOrDefault
ddlClienti.SelectedValue = email.rfCliente
ddlClientiIndexChanged()
End If
End Sub
But while debugging it I see that ddlClienti is = Nothing so the routine fails.
What is the right way to do this? Thanks
I did the same thing using a timer inside the template field
I'm trying to add a new blank row to my gridview whenever the user clicks the Add row button. Ideally, whichever row they click this button, a new row would be inserted just below that row.
I've read through a lot of the previous questions but I still cannot get my gridview to display a new blank row.
Page code:
<table>
...
...
<td colspan="3" align="left" style="border: thin solid #000000; vertical-align: top; background-color: #4B6C9E">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<asp:GridView ID="grdHours" runat="server" AutoGenerateColumns="False" Width="100%" CellPadding="4"
ForeColor="#333333" GridLines="None" >
<AlternatingRowStyle BackColor="White" VerticalAlign="Top" Height="20px"/>
<Columns>
<asp:TemplateField ShowHeader="False" HeaderText="Task">
<ItemTemplate>
<asp:Label ID="BufferLabel" runat="server" Text="" Visible="False"></asp:Label>
<asp:TextBox ID="TaskList" runat="server" CssClass="myDropDownSearch" Width="80%"
onfocus="inputFocus(this)" onblur="inputBlur(this)" value="Select a Task..."></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="SearchEmployees"
MinimumPrefixLength="3"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="TaskList"
ID="AutoCompleteExtender3" runat="server" FirstRowSelected = "false">
</asp:AutoCompleteExtender>
</ItemTemplate>
<ItemStyle Width="15%" />
</asp:TemplateField>
<asp:BoundField DataField="Weekday" HeaderText="Weekday" >
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" Width="4%" />
</asp:BoundField>
<asp:BoundField DataField="Date" DataFormatString="{0:d}" HeaderText="Date" >
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" Width="8%" />
</asp:BoundField>
<asp:TemplateField HeaderText="Hours">
<ItemTemplate>
<asp:Label ID="lblHours" Visible='<%# NOT IsInEditMode %>' runat="server" Text='<%# Eval("Hours") %>' CssClass="hoursLabel" />
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Hours") %>'
Width="90%" Visible='<%# IsInEditMode %>'>
</asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle Width="5%" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Minutes">
<ItemTemplate>
<asp:Label ID="lblMins" Visible='<%# NOT IsInEditMode %>' runat="server" Text='<%# Eval("Minutes") %>' CssClass="hoursLabel" />
<asp:DropDownList ID="DropDownList2" runat="server" CssClass="myDropDown" selectedValue='<%# Eval("Minutes") %>' Visible='<%# IsInEditMode %>' >
<asp:ListItem></asp:ListItem>
<asp:ListItem>0</asp:ListItem>
<asp:ListItem>15</asp:ListItem>
<asp:ListItem>30</asp:ListItem>
<asp:ListItem>45</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle Width="5%" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Activity" >
<ItemTemplate>
<asp:Label ID="lblActivity" Visible='<%# NOT IsInEditMode %>' runat="server" Text='<%# Eval("Activity") %>' CssClass="hoursLabel" />
<asp:DropDownList ID="DropDownList1" runat="server" width="75%" selectedValue='<%# Eval("Activity") %>' Visible='<%# IsInEditMode %>'>
<asp:ListItem Selected="True">Select Activity</asp:ListItem>
<asp:ListItem></asp:ListItem>
<asp:ListItem>Prescope</asp:ListItem>
<asp:ListItem>Scope</asp:ListItem>
<asp:ListItem>Design/Build Configuration</asp:ListItem>
<asp:ListItem>Testing</asp:ListItem>
<asp:ListItem>Training</asp:ListItem>
<asp:ListItem>Implementation/Validation</asp:ListItem>
<asp:ListItem>Maintenance & Ongoing Support</asp:ListItem>
<asp:ListItem>Project Management</asp:ListItem>
<asp:ListItem>Shared Time</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" visible="false" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle Width="20%" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" HeaderText="AddEntries">
<ItemTemplate>
<asp:Button ID="btnHoursRow" runat="server" Text="+" Visible='<%# IsInEditMode %>' OnClick="btnNewEntryRow_Click" />
</ItemTemplate>
<ItemStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" HeaderText="AddNotes">
<ItemTemplate>
<asp:Label ID="lblNotes" Visible='<%# NOT IsInEditMode %>' runat="server" CssClass="hoursLabel" />
<asp:Button ID="btnAddNotes" runat="server" Text="Add Notes" Visible='<%# IsInEditMode %>' />
<asp:ModalPopupExtender ID="btnAddNotes_ModalPopupExtender" runat="server"
DynamicServicePath="" Enabled="True" PopupControlID="pnlNotes"
TargetControlID="btnAddNotes"
OkControlID="btnNotesDone">
</asp:ModalPopupExtender>
</ItemTemplate>
<ItemStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" HeaderText="Validator">
<ItemTemplate>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Whole Numbers Only" ControlToValidate="TextBox1" ValidationGroup="HoursasIntegers"
ValidationExpression="\d+" SetFocusOnError="False" Width="75%" Font-Bold="True" ForeColor="Red" Display="Dynamic"></asp:RegularExpressionValidator>
</ItemTemplate>
<ItemStyle Width="10%" />
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" HeaderText="ErrMessage">
<ItemTemplate>
<asp:Label ID="ActivityErrorMessage" runat="server" Text="You must select an Activity for entered hours." Visible="False" ForeColor="#FF0000" Font-Bold="True"></asp:Label>
</ItemTemplate>
<ItemStyle Width="19%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="TimeNotes">
<ItemTemplate>
<asp:Panel ID="pnlNotes" runat="server" Visible='<%# IsInEditMode %>' Width="75%" BackColor="#4B6C9E" Height="300px">
<table width="100%">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Enter Notes Below:" ForeColor="White" Font-Size="Medium"></asp:Label>
</td>
</tr>
<tr>
<td align="center">
<asp:TextBox ID="txtNotes" runat="server" CssClass="myTextbox"
TextMode="MultiLine" Text='<%# Eval("TimeNotes") %>' Height="200"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnNotesDone" runat="server" Text="Done" />
<asp:Button ID="btnNotesCancel" runat="server" Text="Cancel" OnClick="btnNotesCancel_Click" Visible="False" />
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
<ItemStyle Width="4%" />
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="White" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" Height="20px" VerticalAlign="Top" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</td>
Code behind:
Protected Sub btnNewEntryRow_Click(ByVal sender As Object, ByVal e As EventArgs)
' Dim clickedRow = TryCast(DirectCast(sender, Button).NamingContainer, GridViewRow)
' Dim clickedIndex = clickedRow.RowIndex
'Just hard coded a value for now
BindGrdHours(3)
End Sub
Private Sub BindGrdHours(ByVal rowIndex As Integer)
Dim rowIndex As Integer = 0
If ViewState("CurrentGridTable") IsNot Nothing Then
Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentGridTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count > 0 Then
For i As Integer = 1 To dtCurrentTable.Rows.Count
Dim TaskList As TextBox = DirectCast(grdHours.Rows(rowIndex).Cells(1).FindControl("TaskList"), TextBox)
'Dim TextBoxAge As BoundField
'TextBoxAge.DataField = grdHours.Rows(rowcount).Cells(2).FindControl("Weekday").ToString
'Dim TextBoxAddress As BoundField
'TextBoxAddress.DataField = grdHours.Rows(rowcount).Cells(3).FindControl("Date").ToString
Dim Hours As TextBox = DirectCast(grdHours.Rows(rowIndex).Cells(4).FindControl("TextBox1"), TextBox)
Dim Minutes As DropDownList = DirectCast(grdHours.Rows(rowIndex).Cells(5).FindControl("DropDownList2"), DropDownList)
Dim Activity As DropDownList = DirectCast(grdHours.Rows(rowIndex).Cells(6).FindControl("DropDownList1"), DropDownList)
Dim AddEntries As Button = DirectCast(grdHours.Rows(rowIndex).Cells(7).FindControl("btnHoursRow"), Button)
drCurrentRow = dtCurrentTable.NewRow()
' drCurrentRow("RowNumber") = i + 1
dtCurrentTable.Rows(i - 1)("Task") = TaskList.Text.ToString
dtCurrentTable.Rows(i - 1)("Weekday") = grdHours.Rows(rowIndex).Cells(2).Text.ToString
dtCurrentTable.Rows(i - 1)("Date") = grdHours.Rows(rowIndex).Cells(3).Text.ToString
dtCurrentTable.Rows(i - 1)("Hours") = Hours.Text.ToString
dtCurrentTable.Rows(i - 1)("Minutes") = Minutes.SelectedValue.ToString
dtCurrentTable.Rows(i - 1)("Activity") = Activity.SelectedValue.ToString
dtCurrentTable.Rows(i - 1)("AddEntries") = AddEntries.Text.ToString
dtCurrentTable.Rows(i - 1)("AddNotes") = String.Empty
dtCurrentTable.Rows(i - 1)("Validator") = String.Empty
dtCurrentTable.Rows(i - 1)("ErrMessage") = String.Empty
dtCurrentTable.Rows(i - 1)("TimeNotes") = String.Empty
rowIndex += 1
Next
dtCurrentTable.Rows.Add(drCurrentRow)
ViewState("CurrentGridTable") = dtCurrentTable
grdHours.DataSource = dtCurrentTable
grdHours.DataBind()
Dim txn As TextBox = DirectCast(grdHours.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)
' txn.Focus;
txn.Focus()
End If
End If
enterHours(True)
End Sub
When I click the button, the btnNewEntryRow_Click function is being called, which in turns calls BindGrdHours() successfully but after completion, nothing is happening. The screen still contains the original gridview.
Any ideas on where I'm going wrong? Thanks for looking.
Having some real issues with this and cannot suss out where the problem lies.
I have created a basic car site which as the ability for users to upload pictures. i got a detail page, that hyperlink according the unique ID, which works fine. It all breaks down when i inserted a list view into the equation. I essentially want to make a small gallery, where a user clicks on it and it shows specific details.
It does work, however, if you refer to the image, this is what happens:
Now the images that work do not link at all to its unique ID (says data mismatch). The images that don't work link perfectly fine to its unique ID, but fails to display pictures.
cardata.aspx
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="cardata.aspx.vb" Inherits="WebApplication1.cardata" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
<br />
<br />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="TagsDataSource" Height="23px" Width="130px" CellPadding="4" style="color: #663300" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="Tag" DataNavigateUrlFormatString="CarByTags.aspx?Tag={0}" DataTextField="Tag" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="White" HorizontalAlign="Center" BackColor="#284775" />
<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>
<br />
<asp:SqlDataSource ID="TagsDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:CarDataString %>" ProviderName="<%$ ConnectionStrings:CarDataString.ProviderName %>" SelectCommand="SELECT [Tag] FROM [tags]"></asp:SqlDataSource>
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" GroupItemCount="3">
<AlternatingItemTemplate>
<td runat="server" style="background-color:#FFF8DC;">
<asp:Label ID="Image" runat="server" />
<a href='cardetail.aspx?ID={0}' />
<img src='<%# Eval("Image") %>' height="230" width="400" />
</a>
<br />
</td>
</AlternatingItemTemplate>
<EditItemTemplate>
<td runat="server" style="background-color:#008A8C;color: #FFFFFF;">Image:
<asp:TextBox ID="ImageTextBox" runat="server" Text='<%# Bind("Image") %>' />
<br />
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<br />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
<br /></td>
</EditItemTemplate>
<EmptyDataTemplate>
<table runat="server" style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<EmptyItemTemplate>
<td runat="server" />
</EmptyItemTemplate>
<GroupTemplate>
<tr id="itemPlaceholderContainer" runat="server">
<td id="itemPlaceholder" runat="server"></td>
</tr>
</GroupTemplate>
<InsertItemTemplate>
<td runat="server" style="">Image:
<asp:TextBox ID="ImageTextBox" runat="server" Text='<%# Bind("Image") %>' />
<br />
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<br />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />
<br /></td>
</InsertItemTemplate>
<ItemTemplate>
<td runat="server" style="background-color:#DCDCDC;color: #000000;">Image:
<asp:Label ID="ImageLabel" runat="server" Text='<%# Eval("Image") %>' />
<asp:HyperLink ID="hlEdit" runat="server"
NavigateUrl='<%# Eval("ID", "cardetail.aspx?ID={0}")%>'
ImageUrl="~/Images/edit.png"></asp:HyperLink>
<br /></td>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="groupPlaceholderContainer" runat="server" border="1" style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana, Arial, Helvetica, sans-serif;">
<tr id="groupPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="text-align: center;background-color: #CCCCCC;font-family: Verdana, Arial, Helvetica, sans-serif;color: #000000;">
<asp:DataPager ID="DataPager1" runat="server" PageSize="12">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<SelectedItemTemplate>
<td runat="server" style="background-color:#008A8C;font-weight: bold;color: #FFFFFF;">Image:
<asp:Label ID="ImageLabel" runat="server" Text='<%# Eval("Image") %>' />
<asp:HyperLink ID="hlEdit" runat="server"
NavigateUrl='<%# Eval("ID", "cardetail.aspx?ID={0}")%>'
ImageUrl="~/Images/edit.png"></asp:HyperLink>
<br /></td>
</SelectedItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CarDataString %>" ProviderName="<%$ ConnectionStrings:CarDataString.ProviderName %>" SelectCommand="SELECT [Image] FROM [carclub]"></asp:SqlDataSource>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Car Make" HeaderText="Car Make" SortExpression="Car Make" />
<asp:BoundField DataField="Model" HeaderText="Model" SortExpression="Model" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:BoundField DataField="Engine Size" HeaderText="Engine Size" SortExpression="Engine Size" />
<asp:BoundField DataField="Origin" HeaderText="Origin" SortExpression="Origin" />
<asp:BoundField DataField="BHP" HeaderText="BHP" SortExpression="BHP" />
<asp:BoundField DataField="Layout" HeaderText="Layout" SortExpression="Layout" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="cardetail.aspx?ID={0}" HeaderText="More Details" Text="Details" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="White" HorizontalAlign="Center" BackColor="#284775" />
<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>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CarDataString %>" ProviderName="<%$ ConnectionStrings:CarDataString.ProviderName %>" SelectCommand="SELECT * FROM [carclub]"></asp:SqlDataSource>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
cardetail.aspx
Imports System.Data.OleDb
Public Class cardetail
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
If Request.Params("ID") = "" Then Response.Redirect("cardata.aspx")
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("CarDataString").ConnectionString)
Dim SqlString As String = "SELECT * FROM comments WHERE car_fkId=#f1"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", Request.Params("ID"))
oleDbConn.Open()
Dim dataReader = cmd.ExecuteReader()
GridView2.DataSource = dataReader
GridView2.DataBind()
End If
End Sub
Protected Sub btn_AddComment_Click(sender As Object, e As EventArgs) Handles btn_AddComment.Click
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("CarDataString").ConnectionString)
Dim SqlString As String = "Insert into comments(Author, Comment, Title, car_fkId) Values (#f1,#f2,#f3,#f4)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_author.Text)
cmd.Parameters.AddWithValue("#f2", tb_title.Text)
cmd.Parameters.AddWithValue("#f3", tb_comment.Text)
cmd.Parameters.AddWithValue("#f4", Request.Params("ID"))
oleDbConn.Open()
cmd.ExecuteNonQuery()
''''''fill Gridview2
Dim fillComments As String = "SELECT * FROM comments WHERE car_fkId=#f1"
Dim fillCommentsCmd As OleDbCommand = New OleDbCommand(fillComments, oleDbConn)
fillCommentsCmd.CommandType = CommandType.Text
fillCommentsCmd.Parameters.AddWithValue("#f1", Request.Params("ID"))
Dim dataReader = fillCommentsCmd.ExecuteReader()
GridView2.DataSource = dataReader
GridView2.DataBind()
tb_author.Text = ""
tb_comment.Text = ""
tb_title.Text = ""
End Sub
Protected Sub CheckBoxList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CheckBoxList1.SelectedIndexChanged
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("CarDataString").ConnectionString)
Dim SqlString As String = "INSERT INTO CarTagJunction(Car_fkId,Tag_fkId) VALUES(#f1,#f2)"
oleDbConn.Open()
For Each cb As ListItem In CheckBoxList1.Items
If cb.Selected Then
'here is where we add the join to the table of tags of cars
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", Request.Params("ID"))
cmd.Parameters.AddWithValue("#f2", cb.Value)
cmd.ExecuteNonQuery()
End If
Next
If TextBox1.Text = "" Then Return
Dim newTags = TextBox1.Text.Split(",")
For Each newTag In newTags
Dim newTagSql As String = "INSERT INTO Tags(Tag) VALUES(#f1)"
Dim cmd As OleDbCommand = New OleDbCommand(newTagSql, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", newTag)
cmd.ExecuteNonQuery()
Dim getLastIdCmd As OleDbCommand = New OleDbCommand("SELECT TOP 1 ID from Tags ORDER BY ID DESC", oleDbConn)
Dim dr = getLastIdCmd.ExecuteReader()
dr.Read()
Dim LastId = dr.GetValue(0)
Dim newcmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
newcmd.CommandType = CommandType.Text
newcmd.Parameters.AddWithValue("#f1", Request.Params("ID"))
newcmd.Parameters.AddWithValue("#f2", LastId)
newcmd.ExecuteNonQuery()
Next
End Sub
Protected Sub LoginView1_ViewChanged(sender As Object, e As EventArgs) Handles LoginView1.ViewChanged
End Sub
Protected Sub tb_author_TextChanged(sender As Object, e As EventArgs) Handles tb_author.TextChanged
End Sub
End Class
First, you tagged this as asp.net-mvc3 but the problem has nothing to do to MVC, it seems you are using Web Forms.
I believe that the root of your 2 problems lie within the 2 different templates that you are using for odd and even items in the ListView.
Odd items will render according to this:
<ItemTemplate>
<td runat="server" style="background-color:#DCDCDC;color: #000000;">Image:
<asp:Label ID="ImageLabel" runat="server" Text='<%# Eval("Image") %>' />
<asp:HyperLink ID="hlEdit" runat="server"
NavigateUrl='<%# Eval("ID", "cardetail.aspx?ID={0}")%>'
ImageUrl="~/Images/edit.png"></asp:HyperLink>
<br />
</td>
</ItemTemplate>
And even items according this:
<AlternatingItemTemplate>
<td runat="server" style="background-color:#FFF8DC;">
<asp:Label ID="Image" runat="server" />
<a href='cardetail.aspx?ID={0}' />
<img src='<%# Eval("Image") %>' height="230" width="400" />
</a>
<br />
</td>
</AlternatingItemTemplate>
So, now to your problems:
Odd items won't display the image:
It looks like you are using the wrong path to your images in the ItemTemplate. Try changing your HyperLink like this:
<asp:HyperLink ID="hlEdit" runat="server" NavigateUrl='<%# Eval("ID", "cardetail.aspx?ID={0}")%>' ImageUrl='<%# Eval("Image") %>'></asp:HyperLink>
Hyperlink won't work for even items:
Two things looks wrong here. First, you marked your anchor as singleton (closed the tag like this />).
Apart from that, you are not properly replacing {0} with the databound item's id.
Try changing your anchor tag within AlternatingItemTemplate like this:
<a href='<%# Eval("ID", "cardetail.aspx?ID={0}")%>' >
NOTE: Try to keep it simple and avoid re-inventing the wheel. If you already have a ItemTemplate that works, copy it to the AlternatingItemTemplate and modify the elements that need to be changed. You'll realize that more often than none, you don't even need to use the alternate template...
Your anchor tag has several issues:
The tag is closed early. Then there is a closed </a> without any
opening <a>.
href is incorrect, ID={0} will cause an error when you will try to
convert it to int.
<img> has no relation with the preceding <a> tag.
Your markup should be like this:
<AlternatingItemTemplate>
<td runat="server" style="background-color:#FFF8DC;">
<asp:Label ID="Image" runat="server" />
<a href='<%# Eval("ID", "cardetail.aspx?ID={0}") %>' >
<img src='<%# Eval("Image") %>' height="230" width="400" />
</a>
<br />
</td>
</AlternatingItemTemplate>
After fixing this, if you still have issues, try to debug image url's and href's using client side debugging tool and update your question.
I'm binding data to GridView nested in ListView via ItemDataBound and when I'm paging ListView it's loosing datakey value.
Here is DataBound event:
Protected Sub gvResult_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles gvResult.ItemDataBound
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim dbSrc As New SqlDataSource
dbSrc.SelectParameters.Clear()
Dim gv As GridView = e.Item.FindControl("gvPrices")
Dim currentItem As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
Dim currentDataKey As DataKey = Me.gvResult.DataKeys(currentItem.DataItemIndex)
dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings("hotelbedsConnectionString").ConnectionString
dbSrc.SelectCommandType = SqlDataSourceCommandType.StoredProcedure
dbSrc.SelectCommand = "GetPriceTest"
dbSrc.SelectParameters.Add(New Parameter("SearchID", DbType.String, CStr(Request.QueryString("SearchID"))))
dbSrc.SelectParameters.Add(New Parameter("HotelCode", DbType.String, CStr(currentDataKey.Value)))
gv.DataSource = dbSrc
AddHandler gv.RowCommand, AddressOf MarkSelected
gv.DataBind()
End If
End Sub
I'm using normal paging control in ListView like this one:
<LayoutTemplate>
<div id="itemPlaceholderContainer" runat="server" style="">
<span runat="server" id="itemPlaceholder" />
</div>
<div style="">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NumericPagerField ButtonCount="10" CurrentPageLabelCssClass="CurrentPage" NumericButtonCssClass="PageNumbers"
NextPreviousButtonCssClass="PageNumbers" NextPageText=" > " PreviousPageText=" < " />
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
Error is: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Here is full markup of ListView with nested GridView:
<asp:ListView ID="gvResult" runat="server" DataSourceID="ds_hotels" DataKeyNames="HotelCode">
<EmptyDataTemplate>
<span>No data was returned.</span>
</EmptyDataTemplate>
<ItemTemplate>
<div style="width: 96%; float: left;" class="dashed">
<div style="width: 18%; float: left;">
<asp:HyperLink ID="hlHotelInfo" runat="server" Text="Фотографии и информация" NavigateUrl='<%# Eval("HotelCode", "details/{0}") %>'
ImageUrl='<%# Eval("HotelCode", "hotelfront.ashx?HotelCode={0}") %>' CssClass="img_hotel"></asp:HyperLink></div>
<h2 class="title_hotels">
<asp:HyperLink ID="Label2" runat="server" Text='<%# ShowHotelName(Eval("HotelCode")) %>'
NavigateUrl='<%# Eval("HotelCode", "details/{0}") %>'></asp:HyperLink></h2>
<p>
<asp:Label ID="lblHotelDesc" runat="server" Text='<%# ShowHotelDescr(Eval("HotelCode")) %>' />
</p>
</div>
<asp:GridView runat="server" ID="gvPrices" AutoGenerateColumns="False" GridLines="None"
Width="100%" RowStyle-HorizontalAlign="Center" DataSourceID="ds_prices" DataKeyNames="ID">
<AlternatingRowStyle BackColor="#00FF99" />
<SelectedRowStyle Font-Bold="true" BackColor="BlanchedAlmond" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="addToBasket" runat="server" ImageUrl="~/img/32px/Add.png" ToolTip="Добавить в корзину"
OnCommand="MarkSelected" CommandName="Select" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Стоимость">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# ShowMarkUp(Eval("Price", "{0:#0}")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Currency" HeaderText="Валюта" SortExpression="Currency" />
<asp:BoundField DataField="AdultCount" HeaderText="Взрослых" SortExpression="AdultCount" />
<asp:BoundField DataField="ChildCount" HeaderText="Детей" SortExpression="ChildCount" />
<asp:BoundField DataField="RoomCount" HeaderText="Номеров" SortExpression="RoomCount" />
<asp:BoundField DataField="RoomTypeName" HeaderText="Тип номера" SortExpression="RoomTypename" />
<asp:TemplateField HeaderText="Питание" SortExpression="BoardShortName">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("BoardShortName") %>' ToolTip='<%# ShowToolTip(Eval("BoardShortName")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
<asp:SqlDataSource ID="ds_prices" runat="server" ConnectionString="<%$ ConnectionStrings:hotelbedsConnectionString %>"
SelectCommand="GetPriceTest" CancelSelectOnNullParameter="False" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="SearchID" Type="String" />
<asp:Parameter Name="HotelCode" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholder" runat="server">
</div>
<br />
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NumericPagerField ButtonCount="10" CurrentPageLabelCssClass="CurrentPage" NumericButtonCssClass="PageNumbers"
NextPreviousButtonCssClass="PageNumbers" NextPageText=" > " PreviousPageText=" < " />
</Fields>
</asp:DataPager>
</LayoutTemplate>
</asp:ListView>
Correct question is the half of the answer, yeah...
I shoud rather ask - why there is out of range exception.
The asnwer is here:
currentDataKey = Me.gvResult.DataKeys(currentItem.DisplayIndex)
#Abide, thanks for tryinh to help me!
Make sure that in the data being brought back from the database there is no entry with a null value in your datakey causing a negative index.And try this
Dim currentItem As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
If currentItem.DataItemIndex < Me.gvResult.Count-1 then
Dim currentDataKey As DataKey = Me.gvResult.DataKeys(currentItem.DataItemIndex)
End if
Dim HotelCode As String = currentDataKey("HotelCode") ' where the value in quotes would be the name of your datakey.
I have a nested gridview and I want to get the value of the first gridview and assign it to the commandArgument of a button. Can someone advise how to do it
As you will see in the code below I'm already getting the row index with the following code:
"
Text="Save Changes" />
What I need is the DataField="name" instead
See full code below.
<script language="javascript" type="text/javascript">
function divexpandcollapse(divname) {
var div = document.getElementById(divname);
var img = document.getElementById('img' + divname);
if (div.style.display == "none") {
div.style.display = "block"; img.src = "Images/Icons/minus.jpg";
} else { div.style.display = "none"; img.src = "Images/Icons/plus.jpg"; }
}</script>
<asp:DropDownList ID="DateSelection" runat="server" AutoPostBack="True" Height="21px"
Width="134px">
</asp:DropDownList>
<asp:GridView ID="GV_SL" runat="server" OnRowDataBound="gvUserInfo_RowDataBound"
OnRowCommand="GV_SL_RowCommand" AutoGenerateColumns="False"
DataSourceID="SQL_Weekly" AllowSorting="True">
<Columns>
<asp:TemplateField ItemStyle-Width="50px">
<ItemTemplate>
<a href="JavaScript:divexpandcollapse('div<%# Eval("name") %>');">
<img id="imgdiv<%# Eval("name") %>" width="15px" border="0" src="Images/Icons/plus.jpg" /></a></ItemTemplate>
<ItemStyle Width="40px" />
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="Group" SortExpression="name" />
<asp:BoundField DataField="ASL" HeaderText="SL% Act" ReadOnly="True" SortExpression="ASL" />
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="div<%# Eval("name") %>" style="display: none; position: relative; left: 15px;
overflow: auto">
<asp:GridView ID="gvChildGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Metric" HeaderText=" " HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Actual" HeaderText="Actual" HeaderStyle-HorizontalAlign="Left" />
</Columns>
</asp:GridView>
<br />
<asp:UpdatePanel ID="UP_SecondPanel" runat="server" UpdateMode="Always" >
<ContentTemplate>
<%-- --%>
<asp:TextBox ID="TB_Comments" runat="server" Text="Example: Text will be entered here"
TextMode="MultiLine" Rows="4" Width="510px"></asp:TextBox>
<asp:Button ID="B_Save" runat="server" CommandName="AddText" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Save Changes" />
</ContentTemplate>
</asp:UpdatePanel>
<%-- --%>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Any ideas will be appreceiated
Thanks
I sorted the problem with VB code. See below if it helps someone
Protected Sub GV_SL_RowCommand(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddText") Then
' Retrieve the row index stored in the CommandArgument property.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button
' from the Rows collection.
Dim row As GridViewRow = GV_SL.Rows(index)
Dim GroupName As String = GV_SL.Rows(index).Cells(1).Text
'Rest of the code here
End If
End Sub