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;
}
Related
On a RadGrid I can use the CommandItemTemplate to define my own buttons for, in my case, Save and Cancel the edit (like below)
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server" CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
On the code behind, I set up the ItemCommand.
> protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName.CompareTo("UpdateEdited") == 0)
{
var commandItem = ((GridCommandItem)e.Item);
//Updade code here.
}
}
How can I access the modified row with the modified fields so I can perform an updade?
You should have them in command item and you can access them like this:
GridDataItem item = (GridDataItem)e.Item;
string value = item["ColumnUniqueName"].Text;
Is this what you want ? Just a sample you might need to modify it..
.aspx
<telerik:RadGrid ID="rg" runat="server" AutoGenerateColumns="false"
OnNeedDataSource="rg_NeedDataSource" OnItemCommand="rg_ItemCommand"
MasterTableView-CommandItemDisplay="Top" OnItemDataBound="rg_ItemDataBound">
<MasterTableView EditMode="InPlace">
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server"
CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server"
CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Eval("A") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt" runat="server"
Text='<%# Eval("A") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Text="Edit"
CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate> </EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
dt.Rows.Add("A1");
// Check & Bind
if (dt != null)
{
// Viewstate
ViewState["Data"] = dt;
rg.DataSource = dt;
rg.DataBind();
dt.Dispose();
}
}
}
protected void rg_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
protected void rg_ItemCommand(object sender, GridCommandEventArgs e)
{
// Check
if (e.CommandName == "UpdateEdited")
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
// Loop All
foreach (GridEditableItem item in rg.Items)
{
// Find Control
TextBox txt = item.FindControl("txt") as TextBox;
// Check & Add to DataTable
if (txt != null) dt.Rows.Add(txt.Text.Trim());
}
// Check
if (dt != null && dt.Rows.Count > 0)
{
// Set Viewstate
ViewState["Data"] = dt;
// Bind
rg.DataSource = dt;
rg.DataBind();
// Dispose
dt.Dispose();
}
}
else if (e.CommandName == "CancelAll")
{
// Clear Edit Mode
rg.MasterTableView.ClearChildEditItems();
// Rebind
rg.Rebind();
}
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
// Check
if (e.Item is GridCommandItem)
{
// Find Control
LinkButton btnUpdateEdited = e.Item.FindControl("btnUpdateEdited") as LinkButton;
LinkButton btnCancel = e.Item.FindControl("btnCancel") as LinkButton;
// Get is Edit Mode ?
if (rg.EditIndexes.Count > 0)
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = true;
if (btnCancel != null) btnCancel.Visible = true;
}
else
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = false;
if (btnCancel != null) btnCancel.Visible = false;
}
}
}
I am Using Membership to define roles in Asp.net.Now as per my requirement i need to show the Roles as dynamic Columns of gridview with first two columns as fixed and rest of the columns as per the number of Roles in table but i have no idea of how to meet that as i have never worked on it before..
Here is my static gridview code in aspx page...
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None"
Width="477px">
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkhdr" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkChild" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("col0") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role(Admin)">
<ItemTemplate>
<asp:CheckBox ID="chkAdmin" runat="server" Checked='<%# Eval("col1") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role(DPAO User )">
<ItemTemplate>
<asp:CheckBox ID="chkUser" runat="server" Checked='<%# Eval("col2") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role(GeneralUser)">
<ItemTemplate>
<asp:CheckBox ID="chkgen" runat="server" Checked='<%# Eval("col3") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is the code to load grid with data...
protected void BindGridviewData()
{
var role = from MembershipUser u in Membership.GetAllUsers()
select new
{
User = u.UserName,
Role = string.Join(",", Roles.GetRolesForUser(u.UserName))
};
DataTable dTable = new DataTable();
dTable.Columns.Add("col0", typeof(string));
dTable.Columns.Add("col1", typeof(bool));
dTable.Columns.Add("col2", typeof(bool));
dTable.Columns.Add("col3", typeof(bool));
foreach (MembershipUser u in Membership.GetAllUsers())
{
DataRow dRow = dTable.NewRow();
dRow[0] = u.UserName;
string[] roles = Roles.GetRolesForUser(u.UserName);
dRow[1] = roles.Contains("Admin") ? true : false;
dRow[2] = roles.Contains("DPAO User") ? true : false;
dRow[3] = roles.Contains("GeneralUser") ? true : false;
dTable.Rows.Add(dRow);
}
GridView1.DataSource = dTable;
GridView1.DataBind();
}
In the given Grid I need first two columns as fixed and other column based on value from the Role table from membership...
Any help will be highly appreciated.Thanks in advance..
For dynamically Show , Update roles and Delete records try this:
ASPX:
<asp:GridView ID="GridView1" runat="server" onrowdatabound="GridView1_RowDataBound1"/></asp:GridView>
<asp:Button ID="cmdDelete" runat="server" onclick="cmdDelete_Click1" Text="Delete" />
<asp:Button ID="cmdUpdateRole" runat="server" onclick="cmdUpdateRole_Click" Text="Update Roles" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
DataTable dTable = new DataTable();
dTable.Columns.Add("Select", typeof(bool));
dTable.Columns.Add("Username", typeof(string));
dTable.Columns.Add("Role(Admin)", typeof(bool));
dTable.Columns.Add("Role(DPAO User)", typeof(bool));
dTable.Columns.Add("Role(GeneralUser)", typeof(bool));
foreach (MembershipUser u in Membership.GetAllUsers())
{
DataRow dRow = dTable.NewRow();
dRow[0] = false;
dRow[1] = u.UserName;
string[] roles = Roles.GetRolesForUser(u.UserName);
dRow[2] = roles.Contains("Admin") ? true : false;
dRow[3] = roles.Contains("DPAO User") ? true : false;
dRow[4] = roles.Contains("GeneralUser") ? true : false;
dTable.Rows.Add(dRow);
}
GridView1.DataSource = dTable;
GridView1.DataBind();
}
protected void cmdUpdateRole_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
string username = row.Cells[1].Text;
CheckBox chkAdmin = (CheckBox)row.Cells[2].Controls[0];
CheckBox chkUser = (CheckBox)row.Cells[3].Controls[0];
CheckBox chkgen = (CheckBox)row.Cells[4].Controls[0];
List<string> roles=new List<string>();
if (chkAdmin.Checked)
roles.Add("Admin");
if (chkUser.Checked)
roles.Add("DPAO User");
if (chkgen.Checked)
roles.Add("GeneralUser");
if (Roles.GetRolesForUser(username).Length > 0)
{
Roles.RemoveUserFromRoles(username, Roles.GetRolesForUser(username));
}
if (roles.Count > 0)
{
Roles.AddUserToRoles(username, roles.ToArray());
}
BindGridviewData();
}
}
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox c0 = (CheckBox)e.Row.Cells[0].Controls[0];
CheckBox c2 = (CheckBox)e.Row.Cells[2].Controls[0];
CheckBox c3 = (CheckBox)e.Row.Cells[3].Controls[0];
CheckBox c4 = (CheckBox)e.Row.Cells[4].Controls[0];
c0.Enabled=c2.Enabled =c3.Enabled=c4.Enabled= true;
}
}
protected void cmdDelete_Click1(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = (CheckBox)row.Cells[0].Controls[0];
if (chk.Checked)
{
string username = row.Cells[1].Text;
Membership.DeleteUser(username);
BindGridviewData();
}
}
}
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
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
this is my button click code which fills the grid view
protected void Btnok_Click(object sender, EventArgs e)
{
try
{
if (Page.IsValid)
{
int passoutYear = Convert.ToInt32(passout.SelectedValue);
int courseList = Convert.ToInt32(course.SelectedValue);
StringBuilder sb = new StringBuilder();
string sep = "";
foreach (ListItem li in Branch.Items)
{
if (li.Selected)
{
sb.Append(sep + li.Value);
sep = ",";
}
}
DataTable dt = placedStudentManager.GetPlacedStudentList(sb, passoutYear, courseList);
if (dt != null && dt.Rows.Count != 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
ViewState["dt"] = dt;
}
else
{
noRecordExistOnOkButton.Text = "No Record Exist To Be Inserted For Recruited Students";
Btnsave.Visible = false;
GridView1.Visible = false;
}
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error On Button Btnok_Click:CompanySelected.aspx.cs ", ex);
}
}
this is my button save which save the checked check box gridRow in data base
protected void Btnsave_Click(object sender, EventArgs e)
{
try
{
if (Page.IsValid)
{
int passoutYear = Convert.ToInt32(passout.SelectedValue);
int companyId = Convert.ToInt32(company.SelectedValue);
int courseId = Convert.ToInt32(course.SelectedValue);
string package = txtpackage.Text.Trim();
string venu = txtvenue.Text.Trim();
DateTimeFormatInfo dateInfo = new DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime date = Convert.ToDateTime(vistDate.Text.Trim(), dateInfo);
DataTable gridviewTbl = new DataTable();
DataColumn dc1 = new DataColumn("company_id");
DataColumn dc2 = new DataColumn("course_id");
DataColumn dc3 = new DataColumn("branch_id");
DataColumn dc4 = new DataColumn("student_enrollment");
DataColumn dc5 = new DataColumn("company_visit_date");
DataColumn dc6 = new DataColumn("venu");
DataColumn dc7 = new DataColumn("package");
DataColumn dc8 = new DataColumn("passout_year");
gridviewTbl.Columns.Add(dc1);
gridviewTbl.Columns.Add(dc2);
gridviewTbl.Columns.Add(dc3);
gridviewTbl.Columns.Add(dc4);
gridviewTbl.Columns.Add(dc5);
gridviewTbl.Columns.Add(dc6);
gridviewTbl.Columns.Add(dc7);
gridviewTbl.Columns.Add(dc8);
if (GridView1 != null && GridView1.Rows.Count != 0)
{
int rowCount = GridView1.Rows.Count;
int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("Chek");
if (cb != null && cb.Checked)
{
string enrollmetNo = GridView1.Rows[i].Cells[1].Text.ToString();
int branchId = Convert.ToInt32(GridView1.DataKeys[0].Value);
gridviewTbl.Rows.Add(companyId, courseId, branchId, enrollmetNo, date, venu, package, passoutYear);
}
i++;
}
if (gridviewTbl.Rows.Count != 0)
{
Boolean b = placedStudentManager.SaveSelectdStudent(gridviewTbl);
gridNotExist.Text = "Records Successfully inserted";
}
else
{
gridNotExist.Text = "Please check the record to be inserted";
Btnsave.Visible = true;
GridView1.Visible = true;
}
}
else
{
gridNotExist.Text = "Please Select The Recruited Student, so click the ok button first ";
}
}
else
{
GridView1.Visible = true;
Btnsave.Visible = true;
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error On Button Btnsave_Click:CompanySelected.aspx.cs ", ex);
}
}
now i am doing paging using following code
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = (DataTable)ViewState["dt"];
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
// StringBuilder str=(StringBuilder)ViewState["chk"];
//foreach (GridViewRow row in GridView1.Rows)
//{
//}
}
following is the grid view
<%# Page Language="C#" MasterPageFile="~/Master Pages/AdminMaster.master" AutoEventWireup="true"
CodeFile="CompanySelected.aspx.cs" Inherits="Admin_CompanySelected" Trace="false" Title="Untitled Page" EnableEventValidation="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cph1" runat="Server">
<script language="javascript" type="text/javascript">
function BranchCheckBoxCheck(source, args)
{
var chkBoxListId=document.getElementById ('<%=Branch.ClientID%>');
var chkList=chkBoxListId.getElementsByTagName("input");
for(var i=0;i<chkList.length;i++)
{
if(chkList[i].checked)
{
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphMain" runat="Server">
<div border="1">
<table id="TABLE1" onclick="return TABLE1_onclick()" align="center">
<tr>
<td style="height: 24px">
Passout Year*</td>
<td style="height: 24px">
<asp:DropDownList ID="passout" runat="server">
</asp:DropDownList>
<asp:CustomValidator ID="validateYearForSaveButton" runat="server" ControlToValidate="passout"
ErrorMessage="insert passout year" OnServerValidate="validateYearForSaveButton_ServerValidate"
ValidationGroup="save"></asp:CustomValidator></td>
<td style="height: 24px">
<asp:CustomValidator ID="passoutYearRequire" runat="server" ErrorMessage="Passout Year is Compulsory" ControlToValidate="passout" ValidationGroup="verify" OnServerValidate="passoutYearRequire_ServerValidate">
</asp:CustomValidator>
</td>
<td style="width: 101px; height: 24px;">
</td>
<td style="width: 126px; height: 24px">
</td>
<td style="height: 24px">
</td>
<td style="height: 24px">
</td>
</tr>
<tr>
<td>
Company Name*</td>
<td>
<asp:DropDownList ID="company" runat="server">
</asp:DropDownList>
</td>
<td>
<asp:CustomValidator ID="selectComapnyForSaveButton" runat="server" ControlToValidate="company"
ErrorMessage="Select A Company" OnServerValidate="selectComapnyForSaveButton_ServerValidate"
ValidationGroup="save"></asp:CustomValidator></td>
<td style="width: 101px">
Package*</td>
<td style="width: 126px">
<asp:TextBox ID="txtpackage" runat="server" Width="197px"></asp:TextBox></td>
<td>
<asp:RequiredFieldValidator ControlToValidate="txtpackage" ValidationGroup="save" ID="packageRequire" runat="server" ErrorMessage="Package Require"></asp:RequiredFieldValidator>
</td>
<td>
<asp:Button ID="Btnok" runat="server" Text="Ok" Width="43px" OnClick="Btnok_Click" ValidationGroup="verify" /></td>
</tr>
<tr>
<td>
Course*</td>
<td>
<asp:UpdatePanel id="update" runat="server">
<contenttemplate>
<asp:DropDownList ID="course" runat="server" AutoPostBack="True" OnSelectedIndexChanged="course_SelectedIndexChanged">
</asp:DropDownList>
</contenttemplate>
</asp:UpdatePanel><asp:CustomValidator ID="coursenecessaryForSaveButton" runat="server"
ControlToValidate="course" ErrorMessage="Select A Course" OnServerValidate="coursenecessaryForSaveButton_ServerValidate"
ValidationGroup="save"></asp:CustomValidator></td>
<td>
<asp:CustomValidator ID="courseNecessary" runat="server" ErrorMessage="Select A Course"
OnServerValidate="courseNecessary_ServerValidate" ValidationGroup="verify"></asp:CustomValidator></td>
<td style="width: 101px">
Branch Name*</td>
<td style="width: 126px">
<asp:UpdatePanel id="upchak" runat="server">
<contenttemplate>
<asp:CheckBoxList id="Branch" runat="server" OnSelectedIndexChanged="Branch_SelectedIndexChanged">
</asp:CheckBoxList>
</contenttemplate>
</asp:UpdatePanel>
</td>
<td>
<asp:CustomValidator id="branchRequire" runat="server" ValidationGroup="verify" ClientValidationFunction="BranchCheckBoxCheck" ErrorMessage="Select A Branch"></asp:CustomValidator>
<asp:CustomValidator id="branchrequireForSaveButton" runat="server" ValidationGroup="save" ClientValidationFunction="BranchCheckBoxCheck" ErrorMessage="Select A Branch"></asp:CustomValidator>
<%-- <asp:CustomValidator ID="branchNotexist" runat="server" ErrorMessage="No Branch Exist" ValidationGroup="verify" ControlToValidate="Branch" OnServerValidate="branchNotexist_ServerValidate"></asp:CustomValidator>--%>
</td>
<td>
<asp:Button ValidationGroup="save" ID="Btnsave" runat="server" Text="Save" OnClick="Btnsave_Click" />
</td>
</tr>
<tr>
<td>
Company Visit Date*</td>
<td>
<asp:TextBox ID="vistDate" runat="server" ></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="dateForSaveButton" runat="server" ControlToValidate="vistDate"
ErrorMessage="Visit Date Require" ValidationGroup="save"></asp:RequiredFieldValidator></td>
<td style="width: 101px">
</td>
<td style="width: 126px">
<asp:Label ID="noRecordExistOnOkButton" runat="server" Text="Label" Width="178px"></asp:Label></td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
Venue*
</td>
<td>
<asp:TextBox ID="txtvenue" runat="server"></asp:TextBox>
</td>
<td colspan="4">
<asp:RequiredFieldValidator ID="venRequire" runat="server" ControlToValidate="txtvenue"
ErrorMessage="Insert venu" ValidationGroup="save" Width="73px"></asp:RequiredFieldValidator>
<asp:Label ID="gridNotExist" ForeColor="Red" runat="server" Width="439px"></asp:Label></td>
<td>
</td>
</tr>
<tr>
<td colspan="5" style="height: 16px">
</td>
</tr>
<tr>
<td colspan="5">
<asp:GridView id="GridView1" AllowSorting="true" EnableViewState="true" AutoGenerateColumns="false" runat="server" AllowPaging="True" DataKeyNames="branch_id, default_check, student_id" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="2">
<Columns>
<asp:TemplateField HeaderText="Select Student">
<ItemTemplate>
<asp:CheckBox id="Chek" runat="server" Text="select" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Enrollment No." DataField="enrollment_no" />
<asp:BoundField HeaderText="Course Name" DataField="course_name"/>
<asp:BoundField HeaderText="Branch Name" DataField="branch_name"/>
<asp:BoundField HeaderText="Email Id" DataField="email" />
<asp:BoundField HeaderText="Mobile" DataField="mobile"/>
<asp:BoundField HeaderText="Name" DataField="first_name"/>
<asp:BoundField HeaderText="Surname" DataField="last_name" />
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</asp:Content>
now i want to do paging without loosing check box state and want to save the selectd check box row in data base on save button click how to achieve this please let me know .
I am using dot net framework 2.0...
#PhilPursglove :- My solution is like this
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{ Response.Write(GridView1.PageIndex.ToString());
int d = GridView1.PageCount; bool[] values = new bool[GridView1.PageSize];
CheckBox chb;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
chb = (CheckBox)GridView1.Rows[i].FindControl("Chek");
if (chb != null)
{
values[i] = chb.Checked;
}
}
Session["page" + GridView1.PageIndex] = values;
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = (DataTable)ViewState["dt"];
GridView1.DataBind(); GridView1.Visible = true; Btnsave.Visible = true;
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
if (Session["page" + GridView1.PageIndex] != null)
{ CheckBox chb; bool[] values = (bool[])Session["page" + GridView1.PageIndex];
for (int i = 0; i < GridView1.Rows.Count; i++)
{ chb = (CheckBox)GridView1.Rows[i].FindControl("Chek");
chb.Checked = values[i];
}
}
}
now i want on save button to store those selected chkbox row values to database
First of all, let me restate the problem as I understand it. You have a paged Gridview that has checkboxes on it. You select some of the checkboxes, then move to a different page. When you come back to the original page, you want those checkboxes to still be checked.
There are two elements to doing this, saving the CheckBox state on the old page, and then setting the Checkbox state on the new page.
Saving the CheckBox state on the old page
For every row in the gridview, we need to examine the checkbox to see if it's checked. If it is checked, we record the data id (from DataKeys) into a List. If it isn't checked but it was previously, we remove that id from the list. After we've done this for every row, we save the list in Viewstate.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
List<int> selectedList;
selectedList = (List<int>)this.ViewState["selectedList"];
if (selectedList == null)
{
selectedList = new List<int>();
}
foreach (GridViewRow row in Gridview1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox rowCheckBox;
int rowId;
// Get the Id
rowId = (int)Gridview1.DataKeys[row.RowIndex].Value;
// Get the CheckBox
rowCheckBox = (CheckBox)row.FindControl("Chek");
if (rowCheckBox.Checked)
{
// Don't add the id if it's already in the list
if (selectedList.Contains(rowId))
{ }
else
{
selectedList.Add(rowId);
}
}
else
{
// Remove the id if it was there but now we've unchecked the box
if (selectedList.Contains(rowId))
{
selectedList.Remove(rowId);
}
}
}
}
// Save the list into viewstate
this.ViewState["selectedList"] = selectedList;
// Do the paging as normal
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = (DataTable)ViewState["dt"];
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
}
Setting the CheckBox state on the new page
Now we're in a new page, as we databind each row we need to examine whether the Checkbox needs to be checked. To do this we will get the list out of Viewstate and as we bind each row we look to see if the key for the row is present in the list - if it is, we check the Checkbox. First off we need to attach this method to the Gridview:
<asp:GridView id="GridView1" OnRowDataBound="Gridview1_RowDataBound"
...
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
List<int> selectedList;
int rowId;
CheckBox rowCheckBox;
if (e.Row.RowType == DataControlRowType.DataRow)
{
selectedList = (List<int>)this.ViewState["selectedList"];
if (selectedList == null)
{ }
else
{
rowCheckBox = (CheckBox)e.Row.FindControl("Chek");
// Get the id for the row
rowId = (int)Gridview1.DataKeys[e.Row.RowIndex].Value;
// If the row Id is in the list then check the CheckBox
if (selectedList.Contains(rowId))
{
rowCheckBox.Checked = true;
}
}
}
}
You should now be able to move between pages and your checkboxes will be persistent :-)
At the point where you click your Save button, I would guess that you want to remove the List from Viewstate (this.ViewState.Remove("selectedList")) so that you reset everything. The only other thing that youneed to be aware of here is that my demo code here is based on using a single field in DataKeyNames for the Gridview whereas you're using three fields, so you'll probably want to pick just one field to use for the list - I suspect studentId will do what you want e.g.
rowId = (int)Gridview1.DataKeys(row.RowIndex).Values["studentId"];
When you click your Save button, you need to get the list out of viewstate again, add any checked rows into it from the current page, and then use that to generate your datatable to pass to your manager object.
protected void Btnsave_Click(object sender, EventArgs e)
{
List<int> selectedList;
selectedList = (List<int>)this.ViewState["selectedList"];
if (selectedList == null)
{
selectedList = new List<int>();
}
foreach (GridViewRow row in Gridview1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox rowCheckBox;
int rowId;
// Get the Id
rowId = (int)Gridview1.DataKeys[row.RowIndex].Value;
// Get the CheckBox
rowCheckBox = (CheckBox)row.FindControl("Chek");
if (rowCheckBox.Checked)
{
// Don't add the id if it's already in the list
if (selectedList.Contains(rowId))
{ }
else
{
selectedList.Add(rowId);
}
}
else
{
// Remove the id if it was there but now we've unchecked the box
if (selectedList.Contains(rowId))
{
selectedList.Remove(rowId);
}
}
}
}
int passoutYear = Convert.ToInt32(passout.SelectedValue);
int companyId = Convert.ToInt32(company.SelectedValue);
int courseId = Convert.ToInt32(course.SelectedValue);
string package = txtpackage.Text.Trim();
string venu = txtvenue.Text.Trim();
DateTimeFormatInfo dateInfo = new DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime date = Convert.ToDateTime(vistDate.Text.Trim(), dateInfo);
DataTable gridviewTbl = new DataTable();
...
foreach (int id in selectedList)
{
DataRow newStudentRow;
newStudentRow = gridviewTbl.NewRow;
newStudentRow[0] = id;
newStudentRow[1] = courseid;
...
gridviewTbl.Rows.Add(newStudentRow);
}
if (gridviewTbl.Rows.Count != 0)
{
Boolean b = placedStudentManager.SaveSelectdStudent(gridviewTbl);
if (b)
{
gridNotExist.Text = "Records Successfully inserted";
}
}
else
{
gridNotExist.Text = "Please check the record to be inserted";
Btnsave.Visible = true;
GridView1.Visible = true;
}
}