GridView strange behaviour - asp.net

I have problem on page bellow, in gdvCar_DataBound I add three buttons, when I click on any of them, page go to postback but doesn't enter in gdvCar_RowCommand and then that buttons ( and images that I also add in gdvCar_DataBound) disaper. Grid is then full like gdvCar_DataBound isn't execute. My question is why it doesn't enter at gdvCar_RowCommand ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HMS.library;
using System.Data.SqlClient;
namespace HMS
{
public partial class Cars : System.Web.UI.Page
{
#region fields
private const Int16 PageId = 1;
private String connectionString = "Server=localhost;Database=hms_test;Trusted_Connection=True;";
String[] filters = null;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillProducer();
FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
RestoreFilters();
FillGrid();
}
}
#region events
protected void ddlProducer_Changed(object sender, EventArgs e)
{
if (ddlProducer.SelectedValue != "0")
{
ddlModel.Enabled = true;
FillModel(Convert.ToInt16(ddlProducer.SelectedValue));
}
else
{
ddlModel.SelectedValue = "0";
ddlModel.Enabled = false;
}
upSearch.Update();
}
protected void gdvCar_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Reserve":
{
pnlReserve.Visible = true;
break;
}
case "Phone":
{
break;
}
case "Email":
{
break;
}
}
}
protected void gdvCar_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String id = e.Row.Cells[0].Text;
Image img = new Image();
img.ID = "img_one" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[7].Text;
e.Row.Cells[7].Controls.Add(img);
img = new Image();
img.ID = "img_two" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[8].Text;
e.Row.Cells[8].Controls.Add(img);
img = new Image();
img.ID = "img_three" + id;
img.Width = 96;
img.Height = 96;
img.ImageUrl = "images/car/" + e.Row.Cells[9].Text;
e.Row.Cells[9].Controls.Add(img);
ImageButton imbReserve = new ImageButton();
imbReserve.ID = "res" + id;
imbReserve.Enabled = true;
imbReserve.Width = 48; imbReserve.Height = 48;
imbReserve.ToolTip = "Reserve"; imbReserve.AlternateText = "Reserve";
imbReserve.ImageUrl = "images/icons/key.gif";
imbReserve.CommandName = "Reserve";
imbReserve.CommandArgument = id;
e.Row.Cells[10].Controls.Add(imbReserve);
ImageButton imbPhone = new ImageButton();
imbPhone.ID = "phone" + id;
imbPhone.Enabled = true;
imbPhone.Width = 48; imbPhone.Height = 48;
imbPhone.ToolTip = "Reserve by phone"; imbPhone.AlternateText = "Phone";
imbPhone.ImageUrl = "images/icons/phone.jpg";
imbPhone.CommandName = "Phone";
imbPhone.CommandArgument = id;
e.Row.Cells[11].Controls.Add(imbPhone);
ImageButton imbEmail = new ImageButton();
imbEmail.ID = "email" + id;
imbEmail.Enabled = true;
imbEmail.Width = 48; imbEmail.Height = 48;
imbEmail.ToolTip = "Reserve by email"; imbEmail.AlternateText = "Email";
imbEmail.ImageUrl = "images/icons/email.jpg";
imbEmail.CommandName = "Email";
imbEmail.CommandArgument = id;
e.Row.Cells[12].Controls.Add(imbEmail);
}
}
protected void imbSearch_Click(object sender, ImageClickEventArgs e)
{
StoreFilters();
FillGrid();
}
#endregion
#region functions
private void FillProducer()
{
hmsDataContext hms = new hmsDataContext();
var source = from o in hms.producer_cars
orderby o.name
select new
{
o.id,
o.name
};
foreach (var temp in source)
ddlProducer.Items.Add(new ListItem(temp.name, temp.id.ToString()));
ddlProducer.Items.Insert(0, (new ListItem("all producers", "0")));
}
private void FillModel(int producer_id)
{
hmsDataContext hms = new hmsDataContext();
var source = from o in hms.model_cars
from p in hms.producer_cars
where o.producer_car_id == producer_id && p.id == producer_id
orderby o.name
select new
{
o.id,
o.name
};
ddlModel.Items.Clear();
foreach (var temp in source)
ddlModel.Items.Add(new ListItem(temp.name, temp.id.ToString()));
ddlModel.Items.Insert(0, (new ListItem("all producers", "0")));
}
private void FillGrid()
{
SqlConnection conn = new SqlConnection(connectionString);
String command = #"SELECT car.id AS id, car.price as price, car.weight as weight,
car.year as year, producer_car.name as producer, model_car.name as model, car.number_seats as number_seats, car.photo_one as photo_one,car.photo_two as photo_two,car.photo_three as photo_three, '' as reserver,'' as phone,'' as email
FROM car INNER JOIN model_car on car.model_car_id=model_car.id
INNER JOIN producer_car on model_car.producer_car_id=producer_car.id";
if(filters!=null){
String[] search=new String[5];
search[0]=filters[0]!="0"?"producer_car.id="+filters[0]:"";
search[1]= filters[1] != "0" ? "model_car.id=" + filters[1] : "";
search[2]=filters[2]!=""?"car.color LIKE \'"+filters[2]+"\'":"";
search[3]=filters[3]!=""?"car.price<"+filters[3]:"";
search[4] = filters[4] != "" ? "car.number_seats=" + filters[4] : "";
var a=from f in search
where f!=""
select f;
String filterAddition="";
if(a.Count()>0){
filterAddition=" WHERE ";
foreach ( var b in a){
filterAddition+=" "+b+" AND";
}
filterAddition=filterAddition.EndsWith("AND")?filterAddition.Substring(0,filterAddition.Length-3):filterAddition;
}
command+=filterAddition;
}
SqlCommand comm = new SqlCommand(command, conn);
SqlDataReader r = null;
try
{
comm.Connection.Open();
r =comm.ExecuteReader();
gdvCar.DataSource = r;
gdvCar.DataBind();
r.Close();
}
catch (Exception exc)
{
throw (exc);
}
finally
{
conn.Close();
}
}
private void StoreFilters()
{
filters = new String[5];
filters[0] = ddlProducer.SelectedValue;
filters[1] = ddlModel.SelectedValue;
filters[2] = ddlColor.SelectedValue;
filters[3] = txtStartPrice.Text;
filters[4] = ddlNumber.SelectedValue;
Session["1"] = filters;
}
private void RestoreFilters()
{
if (Session["1"] != null)
{
filters = (String[])Session["1"];
ddlProducer.SelectedValue = filters[0];
ddlProducer_Changed(null, null);
ddlModel.SelectedValue = filters[1];
ddlColor.SelectedValue = filters[2];
txtStartPrice.Text = filters[3];
ddlNumber.SelectedValue = filters[4];
}
}
private void ReserveCar(String FirstName, String LastName, DateTime Start, DateTime End, String Visa, Int16 CarId)
{
hmsDataContext hms = new hmsDataContext();
var a = from c in hms.cars
from rc in hms.rented_cars
where c.id == rc.id_car && c.id == CarId
select new
{
start = rc.start,
end = rc.end
};
Boolean free = false;
if (a.Count() == 0)
{
free = true;
}
else if (a.Count() == 1)
{
if ((a.First().start > End) || (a.First().end < Start))
free = true;
}
else
{
if ((a.First().start > End) || (a.First().end < Start))
free = true;
else if(!free)
{
int n = a.Count();
for (int i = 0; (i < n - 1) && (!free); i++)
{
if (a.ElementAt(i).end < Start && a.ElementAt(i + 1).start > End)
free = true;
i++;
}
if (!free)
{
if (a.ElementAt(n - 1).end < Start)
free = true;
}
}
}
if (free)
{
//insert
}
else
{
//label-nije slobodno za taj termin
}
}
#endregion
}
}
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Cars.aspx.cs" Inherits="HMS.Cars"
MasterPageFile="~/frame.Master" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ContentPlaceHolderID="content" ID="con" runat="server">
<link rel="StyleSheet" href="css/menu.css" type="text/css" media="all">
<asp:ScriptManager ID="sc" runat="server">
</asp:ScriptManager>
<div id="menu">
<ul class="glossymenu">
<li><b>Home</b></li>
<li class="current"><b>Cars</b></li>
<li><b>Boats</b></li>
<li><b>Contact</b></li>
<li><b>Admin</b></li>
</ul>
</div>
<div>
<div>
<asp:UpdatePanel ID="upSearch" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="search">
<fieldset>
<legend>Advanced search</legend>
<table>
<tr>
<td>
Proizvođač:<asp:DropDownList ID="ddlProducer" runat="server" OnSelectedIndexChanged="ddlProducer_Changed"
AutoPostBack="true">
</asp:DropDownList>
</td>
<td>
Model:<asp:DropDownList ID="ddlModel" runat="server" Enabled="false">
</asp:DropDownList>
</td>
<td>
Boja:<asp:DropDownList ID="ddlColor" runat="server">
<asp:ListItem Text="all" Value=""></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
<asp:ListItem Text="White" Value="white"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
Cena do:
<asp:TextBox ID="txtStartPrice" runat="server" MaxLength="10"></asp:TextBox>
din/dan
</td>
<td>
Number seats:<asp:DropDownList ID="ddlNumber" runat="server">
<asp:ListItem Text="-- --" Value=""></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
<asp:ListItem Text="4" Value="4"></asp:ListItem>
<asp:ListItem Text="5" Value="1"></asp:ListItem>
<asp:ListItem Text="6" Value="2"></asp:ListItem>
<asp:ListItem Text="7" Value="3"></asp:ListItem>
<asp:ListItem Text="8" Value="4"></asp:ListItem>
<asp:ListItem Text="9" Value="2"></asp:ListItem>
<asp:ListItem Text="10" Value="3"></asp:ListItem>
<asp:ListItem Text="11" Value="4"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:ImageButton ID="imbSearch" runat="server" ImageUrl="images/icons/search.png"
Width="32" Height="32" ToolTip="Search by choosen criterions" AlternateText="Search"
OnClick="imbSearch_Click" />
</td>
</tr>
</table>
</fieldset>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<br />
<div>
<asp:UpdatePanel ID="upGrid" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:GridView ID="gdvCar" runat="server" OnRowCommand="gdvCar_RowCommand"
OnRowDataBound="gdvCar_DataBound">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div>
<asp:UpdatePanel ID="upTemp" runat="server"><ContentTemplate>
<asp:Panel ID="pnlReserve" runat="server" Visible="false" Width="400" Height="400">
<asp:UpdatePanel ID="upReserve" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</ContentTemplate></asp:UpdatePanel>
</div>
</div>
</asp:Content>

You have to recreate the buttons in RowCreated on every Postback, otherwise their events won't fire.
Save what you need in RowDataBound in the ViewState. In the RowCreated recreate them on Postback(RowDatabound will only be called on Databinding) based on the Viewstate value. Then all controls are available in early page-lifecyle to raise their events.

I believe you can do it in a more elegant way, take a look,
<asp:GridView ...>
<Columns>
<asp:BoundField HeaderText="Some Caption" DataField="Column name from the DataReader result"/>
...
<asp:TemplateField HeaderText="Image..">
<asp:Image runat="server" ImageUrl='<%# String.Format("images/car/{0}", Eval("The column name from the DataReader of the cell 7") %>' />
</asp:TemplateField>
<asp:TemplateField HeaderText="ImageButton..">
<asp:ImageButton runat="server" .../>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then you don't have to add the buttons and the images in the code and takecare of adding them each time the row is created, you just need to fetch the data from the database and set the DataSource of the gridview, and I think you can also get rid of the code fetching the data and replace it with a SqlDataSource.
Take a look at this article about the GridView,
http://msdn.microsoft.com/en-us/library/aa479353.aspx

Related

Unchecking Selected Date in Calendar

I have a asp calendar utility in ascx page. I want to unselect the selected date on second click on the same date. The following are my codes. Kindly help in this.
<%# Control Language="C#" AutoEventWireup="true"CodeFile="Calendar.ascx.cs"Inherits="WebUserControl" %>
<table>
<tr>
<td width="100%">
<asp:DropDownList ID="ddlyear" runat="server"
onselectedindexchanged="ddlyear_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="2014" Value="2014" Selected="True"></asp:ListItem>
<asp:ListItem Text="2015" Value="2015"></asp:ListItem>
<asp:ListItem Text="2016" Value="2016"></asp:ListItem>
<asp:ListItem Text="2017" Value="2017"></asp:ListItem>
<asp:ListItem Text="2018" Value="2018"></asp:ListItem>
<asp:ListItem Text="2019" Value="2019"></asp:ListItem>
<asp:ListItem Text="2020" Value="2020"></asp:ListItem>
<asp:ListItem Text="2021" Value="2021"></asp:ListItem>
<asp:ListItem Text="2022" Value="2022"></asp:ListItem>
<asp:ListItem Text="2023" Value="2023"></asp:ListItem>
<asp:ListItem Text="2024" Value="2024"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="100%" dir="ltr">
<asp:DataList ID="DataList1" runat="server" HorizontalAlign="Center"
RepeatDirection="Horizontal" RepeatColumns="4"
onitemdatabound="DataList1_ItemDataBound"
>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="txt1" runat="server" Text='<%#Eval("Month") %>' Visible="false" Font-Names="Arial"></asp:Label>
<asp:HiddenField ID="hdn1" runat="server" />
<asp:Calendar ID="Calendar1" runat="server" NextPrevFormat="CustomText" SelectionMode="Day" NextMonthText="" PrevMonthText="" Font-Names="A" OtherMonthDayStyle-BorderStyle="NotSet" OtherMonthDayStyle-Wrap="False" OtherMonthDayStyle-ForeColor="#CCCCCC">
<TitleStyle
BackColor="#6EC347"
ForeColor="White"
Height="36"
Font-Size="Large"
Font-Names="Arial"
/>
<SelectedDayStyle
BackColor="Green"
BorderColor="SpringGreen"
/>
</asp:Calendar>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
My code behind for this ascx page is
public partial class WebUserControl : System.Web.UI.UserControl
{
int month = 1;
public event EventHandler YearChanged;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadcalendar();
}
}
private void loadcalendar()
{
DataTable dt = new DataTable();
dt.Columns.Add("Month", typeof(string));
dt.Rows.Add("January");
dt.Rows.Add("February");
dt.Rows.Add("March");
dt.Rows.Add("April");
dt.Rows.Add("May");
dt.Rows.Add("June");
dt.Rows.Add("July");
dt.Rows.Add("August");
dt.Rows.Add("September");
dt.Rows.Add("October");
dt.Rows.Add("Novemeber");
dt.Rows.Add("December");
DataList1.DataSource = dt;
DataList1.DataBind();
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
string year = ddlyear.SelectedValue.ToString();
String str = ((Label)e.Item.FindControl("txt1")).Text;
DateTime Now = DateTime.Now;
DateTime TempDate = new DateTime(Convert.ToInt32(year), month, 1);
// DateTime TempDate = new DateTime(Now.Year,Now.Month, 1);
((Calendar)e.Item.FindControl("Calendar1")).VisibleDate = TempDate;
month = month + 1;
}
}
protected void ddlyear_SelectedIndexChanged(object sender, EventArgs e)
{
loadcalendar();
YearChanged(sender, e);
}
}
My Aspx.cs page code is like this
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
string eid;
string ename = DropDownList2.SelectedValue.ToString();
if (ename == "1")
{
eid = "1";
}
else
{
eid = "2";
}
int cid = Int32.Parse(DropDownList1.SelectedValue.ToString());
//String sqlSelect = String.Format("Select Customer_Id from Customer where Customer_Name='{0}'", cname);
//SqlCommand cmd1 = new SqlCommand(sqlSelect, cnn);
//int cid = (int)cmd1.ExecuteScalar();
DataList dl;
dl = ((DataList)patchCalendar.FindControl("DataList1"));
foreach (DataListItem dli in dl.Items)
{
string month = Convert.ToString(((Label)dli.FindControl("txt1")).Text);
string day = Convert.ToString(((Calendar)dli.FindControl("Calendar1")).SelectedDate.Day);
string year = Convert.ToString(((Calendar)dli.FindControl("Calendar1")).SelectedDate.Year);
string date = ((Calendar)dli.FindControl("Calendar1")).SelectedDate.ToShortDateString();
if (date == "1/1/0001")
{
year = null;
date = null;
day = null;
}
else
{
SqlCommand cmd = new SqlCommand("insert into Patching_Dates values(#cid,#eid,#year,#month,#day,#date)", cnn);
cmd.Parameters.AddWithValue("#cid", cid);
cmd.Parameters.AddWithValue("#eid", eid);
cmd.Parameters.AddWithValue("#year", year);
cmd.Parameters.AddWithValue("#month", month);
cmd.Parameters.AddWithValue("#day", day);
cmd.Parameters.AddWithValue("#date", date);
cmd.ExecuteNonQuery();
}
}
cnn.Close();
string act = "Patching Dates Added";
cnn.Open();
SqlCommand cmd2 = new SqlCommand("insert into Logs values(#Username,#Activity,#Time)", cnn);
cmd2.Parameters.AddWithValue("#Username", (string)(Session["user"]));
cmd2.Parameters.AddWithValue("#Activity", act);
cmd2.Parameters.AddWithValue("#Time", System.DateTime.Now.ToString());
cmd2.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
First check Calendar1 control having value if yes then reset it by this
Calendar1.SelectedDates.Clear();

how to export data from datagrid to excel without images?

I want to display,insert,update,delete in DataGrid (Asp.net and Sqlserver2008) and then i want to export data from datagrid to excel file.
Table Structure
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>'A'</title>
<style type="text`/css">`
.Gridview
{
font-family: Verdana;
font-size: 10pt;
font-weight: normal;
color: black;
}
</style>
<script type="text/javascript">
function ConfirmationBox(username) {
var result = confirm('Are you sure you want to delete ' + username + ' Details?');
if (result) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server" AutoGenerateColumns="false"
CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" ShowFooter="true" HeaderStyle-Font-Bold="true"
HeaderStyle-ForeColor="White" OnRowCancelingEdit="gvDetails_RowCancelingEdit"
OnRowDeleting="gvDetails_RowDeleting" OnRowEditing="gvDetails_RowEditing"
OnRowUpdating="gvDetails_RowUpdating"
OnRowCommand="gvDetails_RowCommand" Height="275px" Width="530px">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server"
ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server"
ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" runat="server"
ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg"
CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server" />
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname"
Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrcity" runat="server" />
<asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity"
Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<EditItemTemplate>
<asp:TextBox ID="txtstate" runat="server" Text='<%#Eval("Designation") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblstate" runat="server" Text='<%#Eval("Designation") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrDesignation" runat="server" />
<asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation"
Text="*" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White"></HeaderStyle>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
<div>
<asp:Button ID="btn_Excel" runat="server" Text="Excel"
onclick="btn_Excel_Click" />
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Reflection;
using System.IO;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
private SqlConnection con = new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtstate");
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Blue;
lblresult.Text = username + " details deleted successfully";
}
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//getting username from particular row
string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName"));
//identifying the control in gridview
ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
//raising javascript confirmationbox whenver user clicks on link button
if (lnkbtnresult != null)
{
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + username + "')");
}
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation = (TextBox)gvDetails.FooterRow.FindControl("txtftrDesignation");
con.Open();
SqlCommand cmd =
new SqlCommand("insert into Employee_Details(UserName,City,Designation) values('"
+ txtUsrname.Text + "','" + txtCity.Text + "','" + txtDesgnation.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Blue;
lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}
protected void btn_Excel_Click(object sender, EventArgs e)
{
this.gvDetails.AllowPaging = false;
this.gvDetails.AllowSorting = false;
this.gvDetails.EditIndex = -1;
this.BindEmployeeDetails();
Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=MyList.xls");
Response.Charset = "";
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
gvDetails.RenderControl(hwriter);
Response.Write(swriter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
//to Render Control
}
}
My code works fine.
But my excel file looks like this
Excel output
So i don't want the images in datagrid to be exported.
How can i do that.
Kindly reply.
Ok i got the solution (From a colleague).
Please vote my answer if its correct.
Explanation:
1.We have to first make a temporary table.
2.Now add only the required column from datagrid.
3.Use temporary table to Export data in Excel.
Code:In the Button click call the function ExportUsersDataTable
protected void btn_Excel_Click(object sender, EventArgs e){ExportUsersDataTable()}
The function definition is:
public void ExportUsersDataTable()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
string sFilename = "UserToRoleMapping.xls";
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = ""; //string.Empty;
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFilename + "\"");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
GridView gvTemp = new GridView();
//Temporary Table for changing the ExcelSheet Headers
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add("User Id");
dtTemp.Columns.Add("User Name");
dtTemp.Columns.Add("City");
dtTemp.Columns.Add("Designation");
dtTemp.AcceptChanges();
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow dr = dtTemp.NewRow();
dr["User Id"] = ds.Tables[0].Rows[i]["UserId"].ToString();
dr["User Name"] = ds.Tables[0].Rows[i]["UserName"].ToString();
dr["City"] = ds.Tables[0].Rows[i]["City"].ToString();
dr["Designation"] = ds.Tables[0].Rows[i]["Designation"].ToString();
dtTemp.Rows.Add(dr);
dtTemp.AcceptChanges();
}
}
if (dtTemp.Rows.Count > 0)
{
gvTemp.DataSource = dtTemp;
gvTemp.DataBind();
gvTemp.RenderControl(htw);
response.Write(sw.ToString());
}
response.End();
}
}
}

Asp.Net set control that in specific row in repeater?

repeater code:
<asp:Repeater ID="Repeater_sorular" runat="server" OnItemCommand="Repeater_sorular_ItemCommand"
OnItemDataBound="Repeater_sorular_ItemBound">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td>
<rad:RadChart ID="RadChart1" runat="server" DefaultType="Pie" Width="700" >
<PlotArea Appearance-FillStyle-FillType="Gradient" Appearance-FillStyle-MainColor="#D90420"
Appearance-FillStyle-SecondColor="#FFAD4A" Appearance-Border-Visible="false">
<EmptySeriesMessage>
<TextBlock Text="Seçilen anket henüz oylanmamıştır.">
<Appearance TextProperties-Font="Tahoma, 10pt, style=Bold">
</Appearance>
</TextBlock>
</EmptySeriesMessage>
</PlotArea>
<ChartTitle>
<TextBlock Appearance-TextProperties-Font="Tahoma">
</TextBlock>
</ChartTitle>
<Appearance ImageQuality="HighQuality" Border-Color="#DFDDDD" TextQuality="ClearTypeGridFit">
</Appearance>
<Series>
<rad:ChartSeries Type="Pie" Appearance-TextAppearance-TextProperties-Color="#FFFFFF"
Appearance-TextAppearance-TextProperties-Font="Tahoma">
</rad:ChartSeries>
</Series>
<Legend Visible="True">
<TextBlock Visible="True">
</TextBlock>
</Legend>
</rad:RadChart>
</td>
<td>
<div style="font-weight: bolder; padding: 5px;">
<%#(((RepeaterItem)Container).ItemIndex+1).ToString() %>.
<%#Eval("Subject")%>
</div>
<asp:BulletedList ID="BulletedList_secenekler" runat="server" DataSource='<%#Eval("Secenekler")%>'
DataTextField="OptionName" DataValueField="OptionId" CssClass="sira_numarali">
</asp:BulletedList>
</td>
</tr>
</table>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
repeater ItemDataBound:
protected void Repeater_sorular_ItemBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
int SurveyId = Int32.Parse(Request.QueryString["anket_id"]);
var sorular = from sr in db.TableSurveyQuestions
where sr.SurveyId == SurveyId
select sr;
//int repeater_satir = 0;
foreach (var soru in sorular)
{
RadChart RadChart1 = new RadChart();
RadChart1 = (RadChart)e.Item.FindControl("RadChart1");
ChartSeries s = RadChart1.Series.GetSeries(0);
s.Appearance.LegendDisplayMode = ChartSeriesLegendDisplayMode.ItemLabels;
s.Clear();
s.Appearance.ShowLabels = true;
s.Appearance.LabelAppearance.Dimensions.Margins.Bottom = 7;
s.PlotArea.IntelligentLabelsEnabled = true;
s.DataYColumn = "VoteCount";
int oy_sayisi = 0;
foreach (var secenek in soru.TableSurveyOptions)
{
int toplam_cevap_sayisi = secenek.TableSurveyVotes.Count;
int dogru_cevap_sayisi = secenek.TableSurveyVotes.Where(a => a.VoteStatus == true).Count();
double yuzde = ((double)dogru_cevap_sayisi / (double)toplam_cevap_sayisi) * 100;
ChartSeriesItem seriesItem = new ChartSeriesItem();
seriesItem.YValue = Math.Round(yuzde, 2);
seriesItem.Name = secenek.OptionName;
seriesItem.ActiveRegion.Tooltip = secenek.OptionName;
seriesItem.Label.TextBlock.Text = secenek.OptionName + " %" + Math.Round(yuzde, 2).ToString();
seriesItem.Appearance.Border.Color = Color.Silver;
seriesItem.Appearance.FillStyle.FillType = Telerik.Charting.Styles.FillType.Solid;
s.Items.Add(seriesItem);
RadChart1.Series.Add(s);
oy_sayisi = secenek.TableSurveyVotes.Count;
}
RadChart1.ChartTitle.TextBlock.Text = db.TableSurveyQuestions.Where(a => a.SurveyId == SurveyId).FirstOrDefault().TableSurvey.Title;
RadChart1.Legend.TextBlock.Text = "Toplam : " + oy_sayisi + " Oy ";
//repeater_satir++;
}
}
}
when I write this code, all charts are showing the last object values. I want to set each chart with different data.
How can I do this.
Thanks.
You could use the ItemIndex property
<asp:Repeater runat="server" ID="myRepeater" OnItemDataBound="myRepeater_ItemDataBound">
<ItemTemplate>
<asp:Label Text='<%# Eval("Id") %>' runat="server" ID="myRepeaterLabel" />
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
switch (e.Item.ItemIndex)
{
case 3:
Label l = (Label)e.Item.FindControl("myRepeaterLabel");
l.Text += "whatever";
break;
default:
break;
}
}
}
Output:
Edited
I am not sure if this would help but you should bind your repeater like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindRepeater();
}
}
private void BindRepeater()
{
var r = Builder<Product>.CreateListOfSize(20).Build();
this.myRepeater.DataSource = r;
this.myRepeater.DataBind();
}
And just modify specific values already bindded in the ItemDataBound event

dynamic textboxes on dropdown's selectedindex

I want to create 5 text boxes created on drop down selected index change and 4 text boxes created if dropdown index is 4. dropdown is inside asp.net updatepanel. There is a button as well inside update panel. When user will click that button, whatever is typed in textboxes, is shown on label.
Please suggest me solution.
May this work
<div>
</div><asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Panel ID="Panel1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"><asp:ListItem Value="1">one </asp:ListItem><asp:ListItem Value="2">Two </asp:ListItem><asp:ListItem Value="3">Three </asp:ListItem><asp:ListItem Value="4">Four</asp:ListItem>
</asp:DropDownList>
<br />
<asp:Button ID="Button2" runat="server" Text="fectchText" onclick="Button2_Click" />
<br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (ViewState["mode"].ToString() == "1")
createTextbox();
ViewState.Add("mode", "1");
}
else
{
ViewState.Add("mode", "0");
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
createTextbox();
}
public void createTextbox()
{
int noOftextbox = Convert.ToInt32(DropDownList1.SelectedItem.Value);
for (int i = 0; i < noOftextbox; i++)
{
TextBox txtbox = new TextBox();
txtbox.ID = "txt" + i;
txtbox.Visible = true;
txtbox.Height = 30;
txtbox.Width = 100;
UpdatePanel1.ContentTemplateContainer.Controls.Add(txtbox);
PlaceHolder1.Controls.Add(txtbox);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
int nocount= Convert.ToInt32(DropDownList1.SelectedItem.Value);
for (int count = 0; count <= nocount-1 ; count++)
{
TextBox txtRead = (TextBox)PlaceHolder1.FindControl("txt" + (count));
Label1.Text += txtRead.Text+"-";
}
}
You can try this.....
for (int i = 0; i < ddlTest.SelectedIndex; i++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i.ToString();
PlaceHolder1.Controls.Add(txt);
}
Change ddlTest.SelectedIndex to your loop condition.....
Hers the solution create txtbox inside updatepanel
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Panel ID="Panel1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="False">
<asp:ListItem Value="1">one </asp:ListItem><asp:ListItem Value="2">Two </asp:ListItem><asp:ListItem Value="3">Three </asp:ListItem><asp:ListItem Value="4">Four</asp:ListItem>
</asp:DropDownList>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
protected void Button1_Click(object sender, EventArgs e)
{
int noOftextbox =Convert.ToInt32(DropDownList1.SelectedItem.Value);
for (int i = 0; i < noOftextbox; i++)
{
TextBox txtbox = new TextBox();
txtbox.ID = i.ToString();
txtbox.Visible = true;
txtbox.Height = 30;
txtbox.Width = 100;
txtbox.Text = "txt" + i.ToString();
PlaceHolder1.Controls.Add(txtbox);
//UpdatePanel1.Controls.Add(txtbox);
//UpdatePanel1.Controls.Add(new LiteralControl("<br/>"));
}
}
You Can try this...
//Add Control into Panel
for (int i = 0; i < 5; i++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i.ToString();
txt.Text = "this is text:" + i.ToString();
pnlTest.Controls.Add(txt);
}
//Fetch Value from Panel
for (int i = 0; i < pnlTest.Controls.Count; i++)
{
string val = ((TextBox)pnlTest.Controls[i]).Text;
}
First loop for add dynamic control into panel and another loop for fetch value from control....

Dynamically change item templet field in grid view

I have a Grid view which contains checkboxex in item templet field. If check box is checked then send mail particular Id. Now When mail is sent the checkbox should replaced by image of sign correct. Now when ever any one have look at the grid view then there should be the image with symbol correct for those whom mail is sent and checkbox for those whom mail is not sent.
//This is the code for my .aspx page
<%# Page Title="Search candidates based on vacancy" Language="C#" MasterPageFile="~/HR Department/hrmasterpage.master"
AutoEventWireup="true" CodeFile="searcAppForVac.aspx.cs" Inherits="HR_Department_searcAppForVac" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<table width="100%">
<tr>
<td>
</td>
</tr>
<tr>
<td align="center" class="tdtitle">
Search Candidates
</td>
</tr>
<tr>
<td>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table width="100%">
<tr>
<td class="RowHeight" width="20%">
Select Company
</td>
<td width="30%">
<asp:DropDownList ID="companyList" runat="server" AppendDataBoundItems="true" AutoPostBack="True"
OnSelectedIndexChanged="companyList_SelectedIndexChanged" Width="150px">
<asp:ListItem Text="-Select Company-" Value="-1"></asp:ListItem>
</asp:DropDownList>
</td>
<td width="20%">
Select Department
</td>
<td width="30%">
<asp:DropDownList ID="deptList" runat="server" AppendDataBoundItems="true" AutoPostBack="True"
onclick="Validate();" OnSelectedIndexChanged="deptList_SelectedIndexChanged"
Width="150px">
<asp:ListItem Value="-1">-Select Department-</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="RowHeight" width="20%">
Select Vacancy
</td>
<td colspan="3" width="*">
<asp:DropDownList ID="vacanyList" runat="server" AppendDataBoundItems="true"
Width="200px" AutoPostBack="True"
onselectedindexchanged="vacanyList_SelectedIndexChanged">
<asp:ListItem Value="-1">-Select Vacancy-</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="4" align="center">
<asp:Label ID="notifyLbl" runat="server" Font-Size="Large" ForeColor="Red"
Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td colspan="4">
<asp:Label ID="titleLbl" runat="server" Font-Size="Large" ForeColor="Red"
Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<td colspan="4">
<asp:GridView ID="appForVacGrid" runat="server" AutoGenerateColumns="False"
CellPadding="4"
onpageindexchanging="appForVacGrid_PageIndexChanging" GridLines="None"
CssClass="mGrid" DataKeyNames="AppId">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
App.ID
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="appIdLbl" runat="server" Text='<%# Eval("AppId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
First Name
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="firstNameLbl" runat="server" Text='<%# Eval("AppFirstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Last Name
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lastNameLbl" runat="server" Text='<%# Eval("AppLastName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Qualification
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="qualiNameLbl" runat="server" Text='<%# Eval("QualiName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Experience
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("TotalExpYear") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
EmailId
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="emailLbl" runat="server" Text='<%# Eval("AppEmailId1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Send Mail
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="sendMailBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle Font-Bold="True" ForeColor="White"
HorizontalAlign="Right" />
<PagerStyle ForeColor="White" HorizontalAlign="Center"
VerticalAlign="Top" CssClass="pgr" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle Font-Bold="True" ForeColor="White"
Font-Size="Medium" HorizontalAlign="Left" />
<AlternatingRowStyle CssClass="alt" />
</asp:GridView>
</td>
</tr>
<tr>
<td colspan="4" align="center">
<asp:Label ID="noSelectionLbl" runat="server" Font-Bold="True"
Font-Size="Large" ForeColor="Red" Text="Label"></asp:Label>
<%--
--%>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<script type="text/javascript">
function alertOnBadSelection() {
var select = document.getElementById('companyList');
if (select.options[select.selectedIndex].value == "-Select Company-") {
alert('Please Select Company!');
return false;
}
}
</script>
</asp:Content>
//This is the code for my .aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
public partial class HR_Department_searcAppForVac : System.Web.UI.Page
{
DataOperation oDo = new DataOperation();
AppVacancyDetailClass objAppVacDetail = new AppVacancyDetailClass();
protected void Page_Load(object sender, EventArgs e)
{
//SET LABLE VISIBILITY TO FALSE.
notifyLbl.Visible = false;
titleLbl.Visible = false;
sendMailBtn.Visible = false;
noSelectionLbl.Visible = false;
//SET GRIDVIEW'S PAGGING PROPERTY.
appForVacGrid.AllowPaging = true;
appForVacGrid.PageSize = 3;
try
{
if (!IsPostBack)
{
Session.Clear();
//DISABLE DEPARTMENT DROPDOWN LIST AND VACANCY DROPDOWN LIST TILL COMPANY IS NOT SELECTED.
deptList.Enabled = false;
vacanyList.Enabled = false;
//FILL COMPANY DROPDOWN LIST HERE.
DataTable objCmpnyTable = oDo.DropDownList("select * from tblCompanyMaster");
if (objCmpnyTable.Rows.Count > 0)
{
companyList.DataSource = objCmpnyTable;
companyList.DataValueField = "CompId";
companyList.DataTextField = "CompName";
companyList.DataBind();
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "There is no company in the list.";
}
}
else
{
//DISABLE ALL DROPDOWN LISTS IF COMPANY DROPDOWN LIST IS SET TO ITS DEFAULT VALUE.
if (companyList.SelectedIndex <= 0)
{
deptList.Enabled = false;
vacanyList.Enabled = false;
}
}
}
catch (Exception)
{
throw;
}
}
protected void companyList_SelectedIndexChanged(object sender, EventArgs e)
{
//DISABLE VACANCY LIST IF DEPARTMENT IS NOT SELECTED.
vacanyList.Enabled = false;
//CLEAR GRIDVIEW WHEN NEW COMPANY IS SELECTED.
appForVacGrid.DataSource = null;
appForVacGrid.DataBind();
try
{
if (companyList.SelectedIndex > 0)
{
deptList.Enabled = true;
deptList.Items.Clear();
string str = "select * from vwCompWiseList where CompId=" + companyList.SelectedValue;
DataTable objDeptTable = oDo.DropDownList("select DeptId,DeptName from vwCompWiseDept where CompId= "+companyList.SelectedValue);
if (objDeptTable.Rows.Count > 0)
{
deptList.DataSource = objDeptTable;
deptList.DataTextField = "DeptName";
deptList.DataValueField = "deptId";
deptList.DataBind();
//SET DEPARTMENT DROPDOWN LIST TO ITS BEFORE FIRST VALUE
deptList.Items.Insert(0, new ListItem("--Select Department--", "-1"));
}
else
{
deptList.Items.Insert(0, new ListItem("--No Departments--", "-1"));
notifyLbl.Visible = true;
notifyLbl.Text = "No Departments Available in " + companyList.SelectedItem.Text;
}
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "Select Company....";
//CLEAR GRIDVIEW
appForVacGrid.DataSource = null;
appForVacGrid.DataBind();
}
}
catch (Exception)
{
throw;
}
}
protected void deptList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (deptList.SelectedIndex > 0)
{
//ENABLE VACANCY DROPDOWN LIST WHEN DEPARTMENT IS SELECTED.
vacanyList.Enabled = true;
//CLEAR OLD VALUE AND REFILL VACANCY DROPDOWN LIST.
vacanyList.Items.Clear();
//GET VACANCIES.
DataTable objVacancytbl = oDo.DropDownList("select VacId,VacTitle from tblVacancyMaster where DeptId =" + deptList.SelectedValue + " and CompId=" + companyList.SelectedValue);
if (objVacancytbl.Rows.Count > 0)
{
vacanyList.DataSource = objVacancytbl;
vacanyList.DataValueField = "VacId";
vacanyList.DataTextField = "VacTitle";
vacanyList.DataBind();
//SET VACANCY DROPDOWN LIST BEFORE FIRST VALUE.
vacanyList.Items.Insert(0, new ListItem("--Select Vacancy--", "-1"));
appForVacGrid.DataSource = null;
appForVacGrid.DataBind();
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "ALL VACANCIES ARE CLOSED IN "+" "+deptList.SelectedItem.Text.ToUpper();
vacanyList.Enabled = false;
appForVacGrid.DataSource = null;
appForVacGrid.DataBind();
}
}
else
{
notifyLbl.Visible = true;
notifyLbl.Text = "Select Department...";
//CLEAR GRIDVIEW.
appForVacGrid.DataSource = null;
appForVacGrid.DataBind();
vacanyList.Enabled = false;
}
}
catch (Exception)
{
throw;
}
}
protected void vacanyList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//FILTER APPLICANTS FOR PERTICULAR VACANCY IN SELECTED DEPARTMETN OF SELECTED COMPANY.
DataTable AppListTbl = objAppVacDetail.GetValue("CompId=" + companyList.SelectedValue + " and DeptId=" + deptList.SelectedValue + " and VacId=" + vacanyList.SelectedValue);
if (AppListTbl.Rows.Count > 0)
{
appForVacGrid.DataSource = AppListTbl;
appForVacGrid.DataBind();
appForVacGrid.Columns[5].Visible = false;
appForVacGrid.Columns[0].Visible = false;
Session.Add("snAppListTbl", AppListTbl);
titleLbl.Visible = true;
titleLbl.Text = AppListTbl.Rows.Count.ToString() + " " + "CANDIDATE(S) ARE ELIGIBLE FOR THE POST OF" + " " + vacanyList.SelectedItem.Text.ToUpper() + ".";
sendMailBtn.Visible = true;
}
}
catch (Exception)
{
throw;
}
}
protected void appForVacGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
//FUNCTION TO PERSIST CHECKBOX STATE IN GRIDVIEW DURING PAGGINATION(POSTBACK).
RememberOldValues();
titleLbl.Visible = true;
titleLbl.Text = ((DataTable)Session["snAppListTbl"]).Rows.Count.ToString() + " " + "CANDIDATE(S) ARE ELIGIBLE FOR THE POST OF" + " " + vacanyList.SelectedItem.Text.ToUpper() + ".";
appForVacGrid.PageIndex = e.NewPageIndex;
appForVacGrid.DataSource = (DataTable)Session["snAppListTbl"];
appForVacGrid.DataBind();
//FUNCTION TO SET CHECKBOX TO ITS PREVIOUS VALUE DURING PAGGINATION.
RepopulateValues();
sendMailBtn.Visible = true;
}
catch (Exception)
{
throw;
}
}
protected void sendMailBtn_Click(object sender, EventArgs e)
{
DataTable AppListTable = ((DataTable)Session["snAppListTbl"]);
//FUNCTION TO PERSIST CHECKBOX STATE IN GRIDVIEW DURING POSTBACK
RememberOldValues();
if (Session["CheckBoxValue"] != null)
{
//RESET PAGGING PROPERTY AND REBIND GRIDVIEW .
appForVacGrid.AllowPaging = false;
appForVacGrid.PageSize = AppListTable.Rows.Count;
appForVacGrid.DataSource = AppListTable;
appForVacGrid.DataBind();
//SET VARIABLES
ArrayList AppIdList = (ArrayList)Session["CheckBoxValue"];
string strToId = "", strMailBody = "", strCcId = "", strBccId = "";
string strFromId = "chetan.patel#sahmed.com";
string strVacTitle = vacanyList.SelectedItem.Text;
string strCompName = companyList.SelectedItem.Text;
string strSubject = "Regarding Selection of Your Resume";
//GET APPLICANT'S EMAILID IF CHECKBOX IS CHECKED.
foreach (GridViewRow Row in appForVacGrid.Rows)
{
int intIndex = (int)appForVacGrid.DataKeys[Row.RowIndex].Value;
if (AppIdList.Contains(intIndex))
{
if (strToId == "")
strToId = ((Label)Row.FindControl("emailLbl")).Text;
else
strToId += "," + ((Label)Row.FindControl("emailLbl")).Text;
}
}
//CREATE MAILBODY.
strMailBody = CommonProcedures.GetMailBody(strVacTitle, strCompName);
//SEND MAIL.
bool isMailSent = true;// CommonProcedures.SendMail(strFromId, strToId, strCcId, strBccId, strSubject, null, strMailBody, false);
if (isMailSent)
{
titleLbl.Visible = true;
titleLbl.Text = "MAIL HAS BEEN SENT TO THE SELECTED APPLICANTS";
sendMailBtn.Visible = true;
}
else
{
titleLbl.Visible = true;
titleLbl.Text = "MAIL SENDING FAIL.... TRY AGAIN LATER..";
sendMailBtn.Visible = true;
}
//RESET PAGGING PROERTY AND REBIND GRIDVIEW.
appForVacGrid.AllowPaging = true;
appForVacGrid.PageSize = 3;
appForVacGrid.DataSource = AppListTable;
appForVacGrid.DataBind();
sendMailBtn.Visible = true;
Session.Clear();
}
else
{
noSelectionLbl.Visible = true;
noSelectionLbl.Text = "NO APPLICANT IS SELECTED...";
sendMailBtn.Visible = true;
}
}
//FUNCTION TO PERSIST STATE OF CHECKBOX IN GRIDVIEW
private void RememberOldValues()
{
ArrayList AppIdList = new ArrayList();
int intIndex = -1;
foreach (GridViewRow Rows in appForVacGrid.Rows)
{
intIndex = (int)appForVacGrid.DataKeys[Rows.RowIndex].Value;
CheckBox sendMailBox = ((CheckBox)Rows.FindControl("sendMailBox"));
if (Session["CheckBoxValue"] != null)
{
AppIdList = (ArrayList)Session["CheckBoxValue"];
}
if (sendMailBox.Checked)
{
if (!AppIdList.Contains(intIndex))
AppIdList.Add(intIndex);
}
else
AppIdList.Remove(intIndex);
}
if (AppIdList.Count > 0 && AppIdList!=null)
{
Session["CheckBoxValue"] = AppIdList;
}
}
//FUNCTION TO SET CHECKBOX VALUE AFTER POSTBACK.
private void RepopulateValues()
{
if (Session["CheckBoxValue"] != null)
{
ArrayList AppIdList = (ArrayList)Session["CheckBoxValue"];
if (AppIdList.Count > 0 && AppIdList != null)
{
foreach (GridViewRow Row in appForVacGrid.Rows)
{
int intIndex = (int)appForVacGrid.DataKeys[Row.RowIndex].Value;
if (AppIdList.Contains(intIndex))
{
CheckBox sendMailBox = (CheckBox)Row.FindControl("sendMailBox");
sendMailBox.Checked = true;
}
}
}
}
}
}
Please Guide me how can I achieve my goal?
<asp:TemplateField>
<HeaderTemplate>
Send Mail
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="sendMailBox" runat="server" />
<asp:img id="CorrectImg" runat="server" imagesrc="yourpathhere" visible="false"/>
</ItemTemplate>
</asp:TemplateField>
In then on your RowDatabound method:
if (Convert.ToBoolean(Databinder.Eval("IsCorrect"))
{
e.Row.FindControl("sendMailBox").Visible = false;
e.Row.FindControl("CorrectImg").Visible = true;
}

Resources