I am unable to see my gridview in the page, no matter what I change. I have used Datasource and Databind, Visible is True, I am thinking at least I should see only the table but nothing. Also I am really sorry that I did not translate this, some things are in Spanish but I think you will understand the context despite the names are in spanish. If this is a problem I can edit and translate.
Thanks.
aspx file:
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Masterpage.Master" CodeBehind="ListarRemateCerrado.aspx.cs"
Inherits="Interfaz.ListarRemateCerrado" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<p>CIERRE DE REMATE</p>
<asp:ListBox ID="lstRemates" runat="server"></asp:ListBox>
<asp:GridView ID="grvRemates" runat="server" AutoGenerateColumns="False" AllowSorting="True" OnPageIndexChanging="grvRemates_PageIndexChanging"
OnSorting="grvRemates_Sorting" AllowPaging="True" PageSize="5" AutoGenerateSelectButton="True"
ShowHeaderWhenEmpty="True" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="ID Remate" SortExpression="Remate">
<ItemTemplate>
<asp:Label ID="lblRemate" runat="server" Text='<%# Eval("Remate") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comision Rematador" SortExpression="Comision">
<ItemTemplate>
<asp:Label ID="lblComision" runat="server" Text='<%#Eval("Comision")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView><br />
<asp:GridView ID="grvRemateSeleccionado" runat="server" AllowSorting="True" PageSize="5" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:Button ID="btnRefrescar" runat="server" Text="Refrescar" OnClick="btnRefrescar_Click" />
<asp:Button ID="btnVolver" runat="server" Text="Volver" OnClick="btnVolver_Click" CausesValidation="false" /> <br />
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>
<asp:Label ID="lblCorrecto" runat="server"></asp:Label>
</asp:Content>
aspx.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dominio;
namespace Interfaz
{
public partial class ListarRemateCerrado : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lstRemates.DataSource = Agencia.Instancia().devolverRemates();
lstRemates.DataTextField = "Datos";
lstRemates.DataValueField = "numero";
lstRemates.DataBind();
if (!IsPostBack)
{
List<Remate> ordenada = Agencia.Instancia().devolverRemates();
ordenada.Sort(new Remate.OrdenarXRemate());
Session["sortedView"] = ordenada;
BindData(ordenada);
Session["filtro"] = "numero";
Session["direccion"] = SortDirection.Ascending;
}
}
protected void btnRefrescar_Click(object sender, EventArgs e)
{
List<Remate> ordenada = Agencia.Instancia().devolverRemates();
ordenada.Sort(new Remate.OrdenarXRemate());
Session["sortedView"] = ordenada;
BindData(ordenada);
Session["filtro"] = "numero";
Session["direccion"] = SortDirection.Ascending;
}
protected void btnVolver_Click(object sender, EventArgs e)
{
Response.Redirect("MenuPrincipalAdmin.aspx");
}
protected void BindData(List<Remate> r)
{
lstRemates.DataSource = r;
lstRemates.DataBind();
}
protected void grvRemates_Sorting(object sender, GridViewSortEventArgs e)
{
List<Remate> ordenada = (List<Remate>)Session["sortedView"];
if (e.SortExpression == "Remate") ordenada.Sort(new Remate.OrdenarXRemate());
if (e.SortExpression == "Comision") ordenada.Sort(new Remate.OrdenarXComision());
if (e.SortExpression == Session["filtro"].ToString().Trim())
{
SortDirection aux = (SortDirection)Session["direccion"];
if (SortDirection.Ascending == aux)
{
Session["direccion"] = SortDirection.Descending;
ordenada.Reverse();
}
else
{
Session["direccion"] = SortDirection.Ascending;
}
}
Session["filtro"] = e.SortExpression;
Session["sortedView"] = ordenada;
BindData(ordenada);
}
protected void grvRemates_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grvRemates.PageIndex = e.NewPageIndex;
BindData((List<Remate>)Session["sortedView"]);
}
protected void grvRemates_SelectedIndexChanged(object sender, EventArgs e)
{
CargarPaquete();
}
private void CargarPaquete()
{
GridViewRow row = grvRemates.SelectedRow;
Label lbl = row.FindControl("lblRemate") as Label;
int codigo = int.Parse(lbl.Text);
grvRemateSeleccionado.DataSource = Agencia.Instancia().devolverLotesRemate(codigo);
grvRemateSeleccionado.DataBind();
}
}
}
You have nowhere set the call databind method for the grid,
grvRemates.DataSource= Agencia.Instancia().devolverRemates();
grvRemates.DataBind();
Related
Cheers,
I have an ASP web form that loads four views: three Gridviews and a Detailsview. Very simply, the first view, Gridview1 is shown to users. All the other views are not .Visible. When the user selects a row from Gridview1, then Gridview2, Gridview3, and the Detailsview becomes visible, and the first Gridview1 becomes not .Visible.
This arrangement is all working perfectly. I've added some <asp:label controls as titles for my views so I can also make them .Visible and not .Visible as well. Also working perfectly.
Now I'm trying to add two <asp:textbox controls to build a search function. Again, I want to use the <asp:textbox control instead of <input type="text" id="txtBadge" name="Badge ID"> so I can also control the .Visible attribute in the CodeBehind. but my <asp:textbox controls seem to be out-of-scope to the CodeBehind. For example, one of my textboxes is called txtBadge. When I type txtBadge in the Codebehind, I get the red squiggly line under it and errors like "The name 'txtBadge' does not exist in the current context".
There are literally hundreds of posts here and in other forums about this particular error, but there's also seemingly hundreds of reasons as well. So I'm hoping someone can help me bring the <asp:textbox controls into the scope of the CodeBehind.
Here is the ASP page:
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeFile="Junk2.aspx.cs" Inherits="CPITraining.Junk2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<style>
.container {
max-width: 1530px;
}
.niceLabels {
margin:15px 0px 15px 0px;
display:inline-block;
font:normal 30px Arial;
}
</style>
<%-- TOP CONTAINER --%>
<div class="container" style="width:1500px">
<div class="row">
<div class="col-md-12">
<div style="background-color:#FFFFFF">
<%-- EMPLOYEE GridView1 Window --%>
<asp:Label ID="EmplList" runat="server" CssClass="niceLabels">Employee Listing</asp:Label>
<div>
<asp:TextBox ID="txtBadge" runat="server" OnInit="txtBadge_Init"></asp:TextBox>
<asp:TextBox ID="txtLast" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</div>
<asp:GridView ID="GridView1" DataKeyNames="badge_id" runat="server" BackColor="White" BorderColor="#999999"
BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black"
GridLines="Vertical" DataSourceID="SqlDataSource1" AllowPaging="True" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="BADGE_ID" HeaderText="BADGE_ID" SortExpression="BADGE_ID" />
<asp:BoundField DataField="FIRSTNAME" HeaderText="FIRSTNAME" SortExpression="FIRSTNAME" />
<asp:BoundField DataField="LASTNAME" HeaderText="LASTNAME" SortExpression="LASTNAME" />
<asp:BoundField DataField="TITLE" HeaderText="TITLE" SortExpression="TITLE" />
<asp:BoundField DataField="deptname" HeaderText="deptname" SortExpression="deptname" />
<asp:BoundField DataField="Column1" HeaderText="Column1" ReadOnly="True" SortExpression="Column1" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
</div>
</div>
</div>
<%-- BOTTOM CONTAINER --%>
<div class="container">
<div class="row">
<div class="col-md-3">
<div style="background-color:#FFFFFF">
<%-- LEFT DETAILS VIEW --%>
<asp:Label ID="EmplHist" runat="server" CssClass="niceLabels">Employee History</asp:Label>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="badge_id"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
DataSourceID="SqlDataSource2" ForeColor="Black" GridLines="Horizontal" Height="50px" Width="125px">
<EditRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<Fields>
<asp:BoundField DataField="BADGE_ID" HeaderText="BADGE_ID" SortExpression="BADGE_ID" />
<asp:BoundField DataField="FIRSTNAME" HeaderText="FIRSTNAME" SortExpression="FIRSTNAME" />
<asp:BoundField DataField="LASTNAME" HeaderText="LASTNAME" SortExpression="LASTNAME" />
<asp:BoundField DataField="TITLE" HeaderText="TITLE" SortExpression="TITLE" />
<asp:BoundField DataField="deptname" HeaderText="deptname" SortExpression="deptname" />
<asp:BoundField DataField="Expr1" HeaderText="Expr1" ReadOnly="True" SortExpression="Expr1" />
</Fields>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
</asp:DetailsView>
</div>
</div>
<div class="col-md-9">
<div class="row" style="background-color:#FFFFFF">
<%-- PROCEDURE CLASSES VIEW --%>
<asp:Label ID="ProcTraining" runat="server" CssClass="niceLabels">Procedure Training Records</asp:Label>
<asp:GridView ID="GridView2" runat="server" DataKeyNames="badge_id"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
DataSourceID="SqlDataSource3" ForeColor="Black" GridLines="Vertical" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
<div class="row"> </div>
<div class="row" style="background-color:#FFFFFF">
<%-- NONPROCEDURE CLASSES VIEW --%>
<asp:Label ID="NonprocTraining" runat="server" CssClass="niceLabels">NonProcedure Training Records</asp:Label>
<asp:GridView ID="GridView3" runat="server" DataKeyNames="badge_id"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
DataSourceID="SqlDataSource4" ForeColor="Black" GridLines="Vertical" AllowPaging="True">
<AlternatingRowStyle BackColor="#CCCCCC" />
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
</div>
</div>
</div>
<p>
/// various <asp:SqlDataSources, etc...
</asp:Content>
Here's the CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace CPITraining
{
public partial class Junk2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (GridView1.SelectedRow != null)
{
//when DETAILS are up
DetailsView1.Visible = true;
GridView1.Visible = false;
EmplList.Visible = false;
EmplHist.Visible = true;
ProcTraining.Visible = true;
NonprocTraining.Visible = true;
}
else
{
//when MAIN list is up
DetailsView1.Visible = false;
GridView1.Visible = true;
EmplList.Visible = true;
EmplHist.Visible = false;
ProcTraining.Visible = false;
NonprocTraining.Visible = false;
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
string TrainingDBConnection = ConfigurationManager.ConnectionStrings["TrainingDBConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(TrainingDBConnection))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
StringBuilder sbCommand = new StringBuilder("Select * from XA_empmas where 1 = 1");
if (txtBadge.Value.Trim != "")
{
sbCommand.Append(" AND BADGE_ID=#txtBadge");
SqlParameter param = new SqlParameter("#txtBadge", txtBadge.Value);
cmd.Parameters.Add(param);
}
if (txtLast.Value.Trim != "")
{
sbCommand.Append(" AND LASTNAME=#txtLast");
SqlParameter param = new SqlParameter("#txtLast", txtBadge.Value);
cmd.Parameters.Add(param);
}
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}
Much thanks for any help!
I have a gridview with the implementation of SelectedIndexChanged.
<asp:GridView ID="gvCalloutTeam" runat="server" OnRowDataBound="gvCalloutTeam_RowDataBound" OnSelectedIndexChanged="gvCalloutTeam_SelectedIndexChanged"
AutoGenerateColumns="False" EnableViewState="False" BackColor="White" BorderColor="#cccccc" BorderWidth="1px" CellPadding="2"
EmptyDataText="No person found" GridLines="None" Width="100%">
<AlternatingRowStyle BackColor="#ededed" />
<Columns>
.......... List of columns..............
</Columns>
<FooterStyle BackColor="#cccccc" ForeColor="Black" />
<HeaderStyle BackColor="#6699cc" Font-Bold="True" ForeColor="White" BorderColor="#cccccc" BorderWidth="1px" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#fefefe" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
I have a check box on the page and CheckedChanged Event implemented on that.
<asp:CheckBox ID="cbTakeOutOrder" runat="server" Text="Take out of order" OnCheckedChanged="cbTakeOutOrder_CheckedChanged" AutoPostBack="true" />
I'm trying to set SelectedIndex of GridView from this event.
protected void cbTakeOutOrder_CheckedChanged(object sender, EventArgs e)
{
if (!cbTakeOutOrder.Checked && gvCalloutTeam.Rows.Count > 0)
gvCalloutTeam.SelectedIndex = 0;
}
But it doesn't fire the SelectedIndexChanged event of GridView. If I select the row on UI, it fires but if I change Index in code, it doesn't fire the event. Is there a way to invoke the event, after changing SelectedIndex in code behind?
protected void gvCalloutTeam_SelectedIndexChanged(object sender, EventArgs e)
{
//////////////////my logic
}
If you are on .net 4.5, you can call SelectRow method on the GridView:
protected void cbTakeOutOrder_CheckedChanged(object sender, EventArgs e)
{
if (!cbTakeOutOrder.Checked && gvCalloutTeam.Rows.Count > 0)
gvCalloutTeam.SelectRow(0);
}
I want to display the "NDA ID" in a label When the user click on the select link in the grid view. But it gives the error as "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index".
Here is my code,
<asp:GridView ID="grdNDA" runat="server" ShowHeaderWhenEmpty="true" EmptyDataText="No Records Found" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateSelectButton="true" Font-Size="Small" Width="95%" onselectedindexchanged="grdNDA_SelectedIndexChanged" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField HeaderText="NDA ID" DataField="NDAid" DataFormatString="ISM/C/NDA/IT/{0}" />
<asp:BoundField HeaderText="Company Name" DataField="ComName" />
<asp:BoundField HeaderText="Country Incorperated" DataField="Country" />
<asp:BoundField HeaderText="Date Created" DataField="Date" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<br>
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
Code behind
protected void grdNDA_SelectedIndexChanged(object sender, EventArgs e)
{
lblValues.Text = "<b>ID:</b> " + grdNDA.SelectedRow.Cells[2].Text;
}
You should change this line
lblValues.Text = "<b>ID:</b> " + grdNDA.SelectedRow.Cells[1].Text;
It worked using this
protected void form1_Load(object sender, EventArgs e)
{
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataRow dr;
dt.Columns.Add("NDAid");
dt.Columns.Add("ComName");
dt.Columns.Add("Country");
dt.Columns.Add("Date");
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company " + i;
dr[2] = "Country " + i;
dr[3] = DateTime.Now;
dt.Rows.Add(dr);
}
grdNDA.DataSource = dt;
grdNDA.DataBind();
}
protected void grdNDA_SelectedIndexChanged(object sender, EventArgs e)
{
lblValues.Text = "<b>ID:</b> " + grdNDA.SelectedRow.Cells[1].Text;
}
ASPX
<form id="form1" runat="server" onload="form1_Load">
<div>
<asp:GridView ID="grdNDA" runat="server" ShowHeaderWhenEmpty="true" EmptyDataText="No Records Found"
AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateSelectButton="true" Font-Size="Small"
Width="95%" OnSelectedIndexChanged="grdNDA_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField HeaderText="NDA ID" DataField="NDAid" DataFormatString="ISM/C/NDA/IT/{0}" />
<asp:BoundField HeaderText="Company Name" DataField="ComName" />
<asp:BoundField HeaderText="Country Incorperated" DataField="Country" />
<asp:BoundField HeaderText="Date Created" DataField="Date" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
</div>
</form>
<asp:GridView ID="gvDisplayImages" runat="server" BackColor="#CCCCCC"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4"
CellSpacing="2" ForeColor="Black" AutoGenerateColumns="false" DataKeyNames="intId"
onrowdeleting="gvDisplayImages_RowDeleting"
onselectedindexchanged="gvDisplayImages_SelectedIndexChanged">
<Columns>
<asp:CommandField SelectText="Delete" ShowDeleteButton="true" />
<asp:BoundField DataField="varImageName" HeaderText="ImageName"
SortExpression="varImageName" />
<asp:TemplateField HeaderText="Preview Image">
<ItemTemplate>
<asp:Image ID ="Img1" runat="server" Height="150" Width="200" ImageUrl='<%#ResolveUrl ("~/" + Eval("varImagePath")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
code for cs page
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
public void BindData()
{
gvDisplayImages.DataSource = bcObj.DisplayImages();
gvDisplayImages.DataBind();
}
protected void gvDisplayImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int intId = Convert.ToInt32(gvDisplayImages.DataKeys[e.RowIndex].Value.ToString());
bcObj.DeleteImage(intId);
BindData();
string filename = Convert.ToString(gvDisplayImages.Rows[e.RowIndex].FindControl("Img1") as Image);
string filepath = "\\Image\\" + filename;
FileInfo file = new FileInfo(filepath);
if (file.Exists)
{
file.Delete();
}
}
Here I am using 3 tier architecture in asp .net By using above code while click delete button in gridview, images are deleted from database successfully. Now please tell me how should I delete image from folder where all images are stored.
Need to use ImageUrl in your code.
like this
string filename = ((Image)(gvDisplayImages.Rows[e.RowIndex].FindControl("Img1"))).ImageUrl;
I am trying to follow and utilize the explained example in ASP.NET website that is about Quiz Engine. I have a Master-Details in the result page where when the user selects one of his answered quesitons in the GridView, the details of that question will be displayed in the DetailsView underneath the GridView. Everything works fine. What I want now is just making the DetailsView (which is the details of the answered question) hidden unless the user selects one of the answered questions. So how to do that?
I set visibility of the DetailsView to false, but I don't know how to hide/show based on the user click on the SELECT option.
My ASP.NET code:
<tr>
<td>
<asp:GridView ID="resultGrid" runat="server" DataKeyNames="QuestionID" SelectedIndex="0"
AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateSelectButton="True" OnSelectedIndexChanged="resultGrid_SelectedIndexChanged" Width="555px">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" HorizontalAlign="Center" />
<Columns>
<asp:BoundField DataField="QuestionID" HeaderText="Question" />
<%--<asp:BoundField DataField="CorrectAnswer" HeaderText="Correct Answer" />--%>
<asp:BoundField DataField="UserAnswer" HeaderText="Your Answer" />
<asp:BoundField DataField="Result" HeaderText="Result" />
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" CssClass="boldtext" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [Question], [Answer1], [Answer2], [Answer3], [QuestionID], [QuestionOrder], [Answer4], [CorrectAnswer], [AnswerExplanation], [QuizID] FROM [Question] WHERE ([QuizID] = #QuizID) ORDER BY [QuestionOrder]">
<SelectParameters>
<asp:SessionParameter Name="QuizID" SessionField="QuizID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
<asp:DetailsView ID="answerDetails" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Height="45px" Width="552px" DataSourceID="SqlDataSource1"
AutoGenerateRows="False" DataKeyNames="QuestionID" Visible="false">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" CssClass="boldtext" Width="100px" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Fields>
<asp:BoundField DataField="Question" HeaderText="Question"
SortExpression="Question" />
<asp:BoundField DataField="Answer1" HeaderText="A"
SortExpression="Answer1" />
<asp:BoundField DataField="Answer2" HeaderText="B"
SortExpression="Answer2" />
<asp:BoundField DataField="Answer3" HeaderText="C"
SortExpression="Answer3" />
<asp:BoundField DataField="Answer4" HeaderText="D"
SortExpression="Answer4" />
<asp:BoundField DataField="CorrectAnswer" HeaderText="Correct Answer"
SortExpression="CorrectAnswer" HeaderStyle-BackColor="lightgreen" />
<asp:BoundField DataField="AnswerExplanation" HeaderText="Explanation"
SortExpression="AnswerExplanation" HeaderStyle-BackColor="lightgreen" />
</Fields>
</asp:DetailsView>
</td>
</tr>
Code-Behind code:
public partial class Results : System.Web.UI.Page
{
Object bShowDetailsView;
protected void Page_Load(object sender, EventArgs e)
{
bShowDetailsView = false;
ArrayList al = (ArrayList)Session["AnswerList"];
if (al == null)
{
Response.Redirect("default.aspx");
}
resultGrid.DataSource = al;
resultGrid.DataBind();
// Save the results into the database.
if (IsPostBack == false)
{
// Calculate score
double questions = al.Count;
double correct = 0.0;
for (int i = 0; i < al.Count; i++)
{
Answer a = (Answer)al[i];
if (a.Result == Answer.ResultValue.Correct)
correct++;
}
double score = (correct / questions) * 100;
string username = HttpContext.Current.User.Identity.Name.ToString().Replace("ARAMCO\\", "");
SqlDataSource userQuizDataSource = new SqlDataSource();
userQuizDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["testConnectionString"].ToString();
userQuizDataSource.InsertCommand = "INSERT INTO [UserQuiz] ([QuizID], [DateTimeComplete], [Score], [Username]) VALUES (#QuizID, #DateTimeComplete, #Score, #Username)";
userQuizDataSource.InsertParameters.Add("QuizID", Session["QuizID"].ToString());
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now.ToString());
// "N4" is for displaying four decimal places, regardless of what the value is
userQuizDataSource.InsertParameters.Add("Score", score.ToString("N4"));
userQuizDataSource.InsertParameters.Add("Username", username);
int rowsAffected = userQuizDataSource.Insert();
if (rowsAffected == 0)
{
// Let's just notify that the insertion didn't
// work, but let' s continue on ...
errorLabel.Text = "There was a problem saving your quiz results into our database. Therefore, the results from this quiz will not be displayed on the list on the main menu.";
}
}
}
protected void resultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataSource1.FilterExpression = "QuestionOrder=" + resultGrid.SelectedValue;
bShowDetailsView = true;
answerDetails.Visible = bShowDetailsView;
}
}
why not make the first record in resultGrid selected by default because the event you are handling is SelectedIndexChanged but not Selected/Unselected (i dont know whether these are there or not)