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.
Related
I have a page with two gridview; one is inside the modal pop up (grdEmpName) and the other is in the page (gvUser). Now, when the user select search button the modal pop up extender will pop up and then search employees. When the user select someone, the selected data should display to the textbox in the another gridview (gvUser).
Everything is working up to selection in modal pop up extender gridview (grdEmpName)but when I select no data pass to the other gridview. (gvUser). I need to display the selected data in the textbox.
ASPX:
<asp:GridView ID="gvUser" runat="server" Width="1024px"
PageSize="10"
AutoGenerateColumns = "False"
AllowSorting="true"
AllowPaging="true"
ShowFooter="True"
OnSorting="gvUser_Sorting"
OnPageIndexChanging="gvUser_PageIndexChanging"
OnRowCreated="gvUser_RowCreated"
CssClass="Grid"
AlternatingRowStyle-CssClass="alt"
PagerStyle-CssClass="pgr"
FooterStyle-HorizontalAlign="center" >
<PagerSettings Mode="NumericFirstLast" PageButtonCount="5" FirstPageImageUrl="~/images/gridview/first_16x16.png" LastPageImageUrl="~/images/gridview/last_16x16.png" />
<Columns>
<asp:TemplateField>
<ItemTemplate >
<asp:ImageButton ID="ibtnEdit" runat="server" ImageUrl="~/images/gridview/file_edit_24x24.png" title = "Edit" _CommandArgument='<%# Eval("USR_ID") & "|Edit|" & CType(Container,GridViewRow).RowIndex & "|-" %>' />
<asp:ImageButton ID="ibtnUpdate" runat="server" ImageUrl="~/images/gridview/file_save_24x24.png" visible="false" title="Update" _CommandArgument='<%# Eval("USR_ID") & "|Update|" & CType(Container,GridViewRow).RowIndex & "|-" %>' />
<asp:ImageButton ID="ibtnCancel" runat="server" ImageUrl="~/images/gridview/file_cancel_24x24.png" Visible="false" title="Cancel" _CommandArgument='<%# Eval("USR_ID")& "|Cancel|" & CType(Container,GridViewRow).RowIndex & "|-" %>' />
<asp:ImageButton ID="ibtnDelete" runat="server" ImageUrl="~/images/gridview/file_delete_24x24.png" title="Delete" _CommandArgument='<%# Eval("USR_ID")& "|Delete|" & CType(Container,GridViewRow).RowIndex & "|" & Eval("USR_IDNTY") %>' />
<asp:ImageButton ID="btnSearchUser" runat="server" ImageUrl="~/images/gridview/file_search_24x24.png" title="Search" _CommandArgument= "btnSearchUser" OnClick = "btnSearchUser_Click" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="ibtnAdd" runat="server" ImageUrl="~/images/gridview/file_add_24x24.png" title="Add" _CommandArgument='<%# Eval("USR_ID") & "|Add|" & CType(Container,GridViewRow).RowIndex & "|-" %>' />
</FooterTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" Width="50px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="User Identity" visible ="false" >
<ItemTemplate>
<asp:Label ID="lblUSR_IDNTY" runat="server" Text='<%# Bind("USR_IDNTY")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblUSR_IDNTY" runat="server" Width="95%" Text='<%# Bind("USR_IDNTY")%>' />
</EditItemTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="User ID" SortExpression="USR_ID">
<ItemTemplate>
<asp:Label ID="lblUSR_ID" runat="server" Text='<%# Bind("USR_ID")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="txtUSR_ID" runat="server" Width="95%" Text='<%# Bind("USR_ID")%>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtUSR_ID" runat="server" Width="95%"/>
</FooterTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="NAME">
<ItemTemplate>
<asp:Label ID="lblNAME" runat="server" Text='<%# Bind("NAME")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNAME" runat="server" Width="95%" Text='<%# Bind("NAME")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNAME" runat="server" Width="95%"/>
</FooterTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Email" SortExpression="EMAIL">
<ItemTemplate>
<asp:Label ID="lblEMAIL" runat="server" Text='<%# Bind("EMAIL")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEMAIL" runat="server" Width="95%" Text='<%# Bind("EMAIL")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEMAIL" runat="server" Width="95%"/>
</FooterTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Active" SortExpression="ACTIVE">
<ItemTemplate>
<asp:CheckBox ID="chkACTIVE" runat="server" Checked ='<%# Bind("ACTIVE")%>' Enabled="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkACTIVE" runat="server" Width="95%" Checked ='<%# Bind("ACTIVE")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkACTIVE" runat="server" Width="95%"/>
</FooterTemplate>
<HeaderStyle Wrap="False" />
<ItemStyle HorizontalAlign="Center" Wrap="False"/>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<div style="height:315px;border-style:hidden;" >
<table class="table" >
<tr>
<td style="padding:5px;" >
<img id="Img1" style="height:24px;width:24px; " runat="server" src="images/no_data_64x64.png" />
</td>
<td style="padding:5px;font-size:large;">
<b>No data found.</b>
</td>
</tr>
</table>
</div>
</EmptyDataTemplate>
<PagerStyle CssClass="pgr" />
<AlternatingRowStyle CssClass="alt" />
<FooterStyle HorizontalAlign="Center" />
<EmptyDataRowStyle CssClass="EmptyData" />
</asp:GridView>
</div>
<%-- Picker--%>
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</cc1:ToolkitScriptManager>
<cc1:ModalPopupExtender runat="server" TargetControlID="hdControl" ID="mdlEmpListProcess" PopupControlID="empPanel" CancelControlID="btnClose" OnCancelScript="getFlickerSolved();" >
</cc1:ModalPopupExtender>
<asp:HiddenField runat="server" ID="hdControl" />
<asp:Panel runat="server" ID="empPanel" Width="909px" Height="300" BorderStyle="Ridge" BorderColor="Gray" Style="display:none;" BackColor="Control">
<table>
<tr>
<td>
<asp:TextBox runat="server" id="txtEmpName" CssClass="textbox" Width="240"></asp:TextBox>
<asp:Button runat="server" ID="btnSearchEmp" CssClass="button" Text="SEARCH" OnClientClick="getFlickerSolved();"/>
<asp:Button runat="server" ID="btnClose" CssClass="button" Text="CLOSE" />
</td>
</tr>
</table> <br />
<div style="overflow:scroll; width:882px; height:233px;">
<asp:GridView runat="server" ID="grdEmpName" Width="863px" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" Height="35px" GridLines="Vertical">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton runat="server" ID="optEmp" AutoPostBack="true" _CommandArgument= "Select" OnCheckedChanged="selectedEmployee" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="USR_ID" HeaderText="USER ID"/>
<asp:BoundField DataField="NAME" HeaderText="NAME"/>
<asp:BoundField DataField="EMAIL" HeaderText="EMAIL ADDRESS">
<HeaderStyle Width="300px" />
</asp:BoundField>
</Columns>
<RowStyle CssClass="rowStyle" />
<HeaderStyle CssClass="headerStyle" BackColor="Black" Font-Bold="True" ForeColor="White" />
<FooterStyle BackColor="#CCCCCC" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
</div>
</asp:Panel>
<%-- End Picker--%>
Now, here's may code for selectedEmployee (Radio Button)
Protected Sub selectedEmployee(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lnBTNDone As RadioButton = DirectCast(sender, RadioButton)
Dim row As GridViewRow = DirectCast(lnBTNDone.NamingContainer, GridViewRow)
Dim RowIndex As Integer = gvUser.EditIndex
Dim dt As New DataTable
dt = TryCast(Session("dbCache_User"), DataView).Table.Copy
Dim dv As New DataView(dt, "", "USR_IDNTY", DataViewRowState.OriginalRows)
Dim s As String = TryCast(gvUser.Rows(RowIndex).FindControl("lblUSR_IDNTY"), Label).Text
Dim idx As Integer = dv.Find(s)
dv(idx)("USR_ID") = row.Cells(1).Text
dv(idx)("NAME") = row.Cells(2).Text
dv(idx)("EMAIL") = row.Cells(3).Text
gvUser.DataSource = dv
gvUser.DataBind()
Me.mdlEmpListProcess.Hide()
End Sub
But I've encounter this error when debugging system.data.dataexception was unhandled by user code. Cannot set Name when passing the value.
dv(idx)("NAME") = row.Cells(2).Text
as per you comment NAME is readonly field error given at runtime than you make is readonly false as below , add same line in your code after reading value
dt.Columns["NAME"].ReadOnly = false
Working example
DataTable dataTable = new DataTable("dataTable");
DataColumn dataColumn = new DataColumn("dataColumn");
dataTable.Columns.Add(dataColumn);
// Add ten rows.
DataRow dataRow;
for (int i = 0; i < 10; i++)
{
dataRow = dataTable.NewRow();
dataRow["dataColumn"] = "item " + i;
dataTable.Rows.Add(dataRow);
}
dataTable.AcceptChanges();///add this line in your code
var dv = new DataView(dataTable, "", "dataColumn", DataViewRowState.OriginalRows);
int index = dv.Find("item 1");
if (index == -1)
Console.WriteLine("Product not found");
else
dv[index]["dataColumn"] = "item 1000";
I suggest first check you are able to find row or not
int idx = dv.Find(s);
if (index == -1)
{
Console.WriteLine ("Product not found");
}
else
{
dv[index]["columnname"] = "value";
}
I'm working with my GridView table in ASP.Net.
First when I click the Edit link button in my GridView I will be able to edit it with Textbox and dropdownlist.
Here's the image of my GridView.
So the Business Unit was enabled but the Division, Sub-Division, Classification and Sub-Classification are not.
My problem is that when I select the Business Unit, the dropdownlist Division should be enabled and be able to select the value according to the Business Unit that I selected and so on. So the next dropdownlist will be dependent on the first dropdownlist that you selected. I searched about this on the internet already and tried different solutions but I'm still confused and don't know how it will work.
Here's my code in ASP.Net
<asp:GridView ID="gvGroup" runat="server" AllowPaging="false"
AllowSorting="true" AutoGenerateColumns="False" BorderColor="Silver"
BorderWidth="1px" Height="104px" ShowFooter="true" ShowHeader="true"
style="margin-right: 0px" Width="77%">
<RowStyle Font-Names="Arial" Font-Size="9pt" HorizontalAlign="Center" />
<Columns>
<asp:TemplateField HeaderStyle-BackColor="#666666"
HeaderStyle-ForeColor="White" HeaderStyle-Width="10px" HeaderText=""
ItemStyle-Width="10px">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
<HeaderStyle BackColor="#666666" ForeColor="White" />
<ItemStyle Width="10px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="" ItemStyle-Width="140px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblMasterID" runat="server" Text='<%#Bind("MASTERID") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="140px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="" ItemStyle-Width="140px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblSEQID" runat="server" Text='<%#Bind("SEQID") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="140px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-BackColor="#666666" HeaderStyle-Font-Size="9pt"
HeaderStyle-ForeColor="White" HeaderText="Job Title" ItemStyle-Font-Size="9pt"
ItemStyle-Width="140px">
<ItemTemplate>
<asp:Label ID="lblJobTitle" runat="server" Text='<%#Bind("JOBTITLE") %>'
Width="140px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtJT" runat="server" CssClass="ehr_textbox"
Text='<%#BIND("JOBTITLE") %>' Width="140px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtJobTitleAdd" runat="server" Width="110px">
</asp:TextBox>
</FooterTemplate>
<HeaderStyle BackColor="#666666" Font-Size="9pt" ForeColor="White" />
<ItemStyle Font-Size="9pt" Width="140px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-BackColor="#666666" HeaderStyle-Font-Size="9pt"
HeaderStyle-ForeColor="White" HeaderText="Business Unit"
ItemStyle-Font-Size="9pt" ItemStyle-Width="140px">
<ItemTemplate>
<asp:Label ID="lblBusinessUnit" runat="server"
Text='<%#Bind("BUSINESS_UNIT") %>' Width="140px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_gvBusinessUnit" runat="server" CssClass="ehr_dropdown"
Width="140px">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlBusinessUnitAdd" runat="server" Width="110px">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle BackColor="#666666" Font-Size="9pt" ForeColor="White" />
<ItemStyle Font-Size="9pt" Width="140px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-BackColor="#666666" HeaderStyle-Font-Size="9pt"
HeaderStyle-ForeColor="White" HeaderText="Division" ItemStyle-Font-Size="9pt"
ItemStyle-Width="140px">
<ItemTemplate>
<asp:Label ID="lblDivision" runat="server" Text='<%#Bind("DIVISION") %>'
Width="140px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_gvDivision" Enabled="false" runat="server" CssClass="ehr_dropdown"
Width="140px">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDivisionAdd" runat="server" Width="110px">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle BackColor="#666666" Font-Size="9pt" ForeColor="White" />
<ItemStyle Font-Size="9pt" Width="140px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-BackColor="#666666" HeaderStyle-Font-Size="9pt"
HeaderStyle-ForeColor="White" HeaderText="Sub-Division"
ItemStyle-Font-Size="9pt" ItemStyle-Width="140px">
<ItemTemplate>
<asp:Label ID="lblSubDivision" runat="server" Text='<%#Bind("SUB_DIVISION") %>'
Width="140px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_gvSubDivision" Enabled="false" runat="server" CssClass="ehr_dropdown"
Width="140px">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlSubDivisionAdd" runat="server" Width="110px">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle BackColor="#666666" Font-Size="9pt" ForeColor="White" />
<ItemStyle Font-Size="9pt" Width="140px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-BackColor="#666666" HeaderStyle-Font-Size="9pt"
HeaderStyle-ForeColor="White" HeaderText="Classification"
ItemStyle-Font-Size="9pt" ItemStyle-Width="140px">
<ItemTemplate>
<asp:Label ID="lblClassification" runat="server"
Text='<%#Bind("CLASSIFICATION") %>' Width="140px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_gvClassification" Enabled="false" runat="server"
CssClass="ehr_dropdown" Width="140px">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlClassification" runat="server" Width="110px">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle BackColor="#666666" Font-Size="9pt" ForeColor="White" />
<ItemStyle Font-Size="9pt" Width="140px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-BackColor="#666666" HeaderStyle-Font-Size="9pt"
HeaderStyle-ForeColor="White" HeaderText="Sub-Classification"
ItemStyle-Font-Size="9pt" ItemStyle-Width="140px">
<ItemTemplate>
<asp:Label ID="lblSubClassification" runat="server"
Text='<%#Bind("SUB_CLASSIFICATION") %>' Width="140px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_gvSubClassification" Enabled="false" runat="server"
CssClass="ehr_dropdown" Width="140px">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlSubClassification" runat="server" Width="110px">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle BackColor="#666666" Font-Size="9pt" ForeColor="White" />
<ItemStyle Font-Size="9pt" Width="140px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-BackColor="#666666" ItemStyle-Font-Size="9pt">
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server" CommandName="Delete"
OnClientClick="return confirm('Do you want to delete?')" Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="btnAdd" runat="server" CommandName="Add"
OnClick="AddgvGroup" Text="Add"></asp:LinkButton>
</FooterTemplate>
<HeaderStyle BackColor="#666666" />
<ItemStyle Font-Size="9pt" />
</asp:TemplateField>
<asp:CommandField HeaderStyle-BackColor="#666666" HeaderStyle-Width="10px"
ItemStyle-Font-Size="9pt" ItemStyle-Width="10px" ShowEditButton="True">
<HeaderStyle BackColor="#666666" />
<ItemStyle Font-Size="9pt" />
</asp:CommandField>
</Columns>
<PagerStyle Font-Size="9pt" HorizontalAlign="Right" />
<EmptyDataTemplate>
<div style="width: 100%; font-size: 10pt; text-align: center; color: Red;">
No record found.
</div>
</EmptyDataTemplate>
<HeaderStyle BackColor="DarkGray" Font-Bold="True" Font-Names="Arial"
Font-Size="9pt" ForeColor="White" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="Gainsboro" />
</asp:GridView>
And here's my code in VB.Net
Protected Sub gvGroup_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvGroup.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
Dim ddlBusinessUnit As DropDownList = DirectCast(e.Row.FindControl("ddl_gvBusinessUnit"), DropDownList)
'bind dropdown-list
Dim sqlstr As String
Dim dt As DataTable = New DataTable()
sqlstr = "Select BUSINESS_UNIT from BUSINESS_UNIT_TBL"
dt = ehr_utils.DataTable(sqlstr)
ddlBusinessUnit.DataSource = dt
ddlBusinessUnit.DataTextField = "BUSINESS_UNIT"
ddlBusinessUnit.DataValueField = "BUSINESS_UNIT"
ddlBusinessUnit.DataBind()
Dim dr As DataRowView = TryCast(e.Row.DataItem, DataRowView)
ddlBusinessUnit.SelectedValue = dr("BUSINESS_UNIT").ToString()
End If
End If
End Sub
Any idea of how can I possibly do that? And I tried also the OnSelectedIndexChanged
First you need to add an OnSelectedIndexChanged to ddl_gvBusinessUnit and set AutoPostBack to true
<asp:DropDownList ID="ddl_gvBusinessUnit" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_gvBusinessUnit_SelectedIndexChanged">
And then in code behind
protected void ddl_gvBusinessUnit_SelectedIndexChanged(object sender, EventArgs e)
{
//cast the sender back to a dropdownlist
DropDownList dropDownList1 = sender as DropDownList;
//get the selectedvalue
string value = dropDownList1.SelectedValue;
//find the other dropdownlist in the correct row by using the editindex
DropDownList dropDownList2 = gvBusinessUnit.Rows[gvBusinessUnit.EditIndex].FindControl("DropDownList2") as DropDownList;
//do stuff with the other dropdownlist, like give it a color or add database values based on the first dropdownlist
dropDownList2.BackColor = Color.Red;
}
VB
Protected Sub ddl_gvBusinessUnit_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
'cast the sender back to a dropdownlist
Dim dropDownList1 As DropDownList = CType(sender,DropDownList)
'get the selectedvalue
Dim value As String = dropDownList1.SelectedValue
'find the other dropdownlist in the correct row by using the editindex
Dim dropDownList2 As DropDownList = CType(gvBusinessUnit.Rows(gvBusinessUnit.EditIndex).FindControl("DropDownList2"),DropDownList)
'do stuff with the other dropdownlist, like give it a color or add database values based on the first dropdownlist
dropDownList2.BackColor = Color.Red
End Sub
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 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