Edit button in Gridview not working - c#

I am trying to use grid view to display a join of several tables(Empdetail,Department,Country,State,City,Qualification). The main table(Empdetail) has different IDs(eg DeptID) which refer to the primary key ID present in the tables. I want department(and other fields) to appear as dropdown choice while updating the gridview but I am facing issues while populating the drop down list and making the edit button fire. The following is the code.
.ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Database.aspx.cs" Inherits="Default2" %>
<!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 runat="server">
<title>Employee Database</title>
<script src="Themes/js/bootstrap.js" type="text/javascript"></script>
<script src="Themes/js/jquery.min.js" type="text/javascript"></script>
<script src="Themes/js/npm.js" type="text/jahttp://www.aspsnippets.com/Articles/Simple-Insert-Select-Edit-Update-and-Delete-in-ASPNet-GridView-control.aspxvascript"></script>
<script src="Themes/js/bootstrap.min.js" type="text/javascript"></script>
<script type = "text/javascript" src = "Scripts/jquery-1.3.2.min.js"></script>
<script type = "text/javascript" src = "Scripts/jquery.blockUI.js"></script>
<script type = "text/javascript">
//to create a loading effect
function BlockUI(elementID) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(function() {
$("#" + elementID).block({ message: '<table align = "center"><tr><td>' +
'<img src="Images/loadingAnim.gif"/></td></tr></table>',
css: {},
overlayCSS: {backgroundColor:'#000000',opacity: 0.6, border:'3px solid #63B2EB'
}
});
});
prm.add_endRequest(function() {
$("#" + elementID).unblock();
});
}
$(document).ready(function() {
BlockUI("dvGrid");
$.blockUI.defaults.css = {};
});
</script>
<link href="Themes/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css" />
<link href="Themes/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="Themes/css/bootstrap-theme.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div id = "dvGrid">
<asp:ScriptManager runat="server" ID="sm">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width = "900px" AlternatingRowStyle-BackColor = "#b3e6ff"
AutoGenerateColumns="false" AllowPaging="true" OnRowDataBound="OnRowDataBound"
HeaderStyle-BackColor = "#0080ff" DataKeyNames="ID"
PageSize="10" class="table table-bordered" ShowFooter="true"
onrowediting="EditEmployee" onrowupdating="UpdateEmployee"
onrowcancelingedit="CancelEdit" OnRowDeleting="DeleteEmployee"
EmptyDataText="No records Selected.">
<Columns >
<asp:TemplateField >
<ItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%# Eval("ID") %>' /><!--Primary key,no update and insert,auto generated-->
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "EmpCode">
<ItemTemplate>
<asp:Label ID="lblEmpCode" runat="server"
Text='<%# Eval("EmpCode")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpCode" runat="server"
Text='<%# Eval("EmpCode")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmpCode" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server"
Text='<%# Eval("EmpName")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server"
Text='<%# Eval("EmpName")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtName" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "DOJ">
<ItemTemplate>
<asp:Label ID="lblDOJ" runat="server"
Text='<%# Eval("DOJ")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDOJ" runat="server"
Text='<%# Eval("DOJ")%>'>
</asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDOJ" class="form-control" Width = "100px"
MaxLength = "15" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "120px" HeaderText = "Department">
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server"
Text='<%# Eval("DeptName")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID = "Depddl" runat="server" Width="100px" >
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox class="form-control" ID="txtDepartment" Width = "140px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server"
Text='<%# Eval("CoName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCountry" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "State">
<ItemTemplate>
<asp:Label ID="lblState" runat="server"
Text='<%# Eval("SName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtState" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server"
Text='<%# Eval("CiName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCity" class="form-control" Width = "60px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "Qualification">
<ItemTemplate>
<asp:Label ID="lblQualification" runat="server"
Text='<%# Eval("QName")%>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtQualification" class="form-control" Width = "80px"
MaxLength = "5" runat="server">
</asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("ID")%>' OnClick = "DeleteEmployee"
OnClientClick = "return confirm('Do you want to delete?')"
Text = "Delete" >
</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add"
class="btn-primary" type="button" OnClick = "AddNewEmployee"/>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Codebehind(aspx.cs/c#)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
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.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
string constr = ConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
//Find the DropDownList in the Row
SqlConnection con = new SqlConnection(constr);
DropDownList Depddl = (DropDownList)e.Row.FindControl("Depddl");
string query = "SELECT ID,DeptName FROM Department;";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
Depddl.DataSource = GetData(cmd);
Depddl.DataTextField = "DeptName";
Depddl.DataValueField = "ID";
Depddl.DataBind();
con.Close();
//Add Default Item in the DropDownList
Depddl.Items.Insert(0, new ListItem("Please select"));
//Select the Department ofEmployee in DropDownList
string Department = (e.Row.FindControl("lblDepartment") as Label).Text;
Depddl.Items.FindByValue(Department).Selected = true;
}
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
string city = (GridView1.Rows[e.RowIndex].FindControl("Depddl") as DropDownList).SelectedItem.Value;
string ID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblID")).Text;
string EmpCode = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtEmpCode")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string DOJ = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtDOJ")).Text;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Empdetail set EmpName=#EmpName," + "EmpCode=#EmpCode,"+ "DOJ=#DOJ where ID=#ID; " +
"select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ, "+
"Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from "+
"Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID "+
"JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID "+
"JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Parameters.Add("#EmpCode", SqlDbType.VarChar).Value = EmpCode;
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = Name;
cmd.Parameters.Add("#DOJ", SqlDbType.VarChar).Value = DOJ;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
protected void DeleteEmployee(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from Empdetail where " +
"ID=#ID;" +
"select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ, Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private void BindData()
{
string query = "select Empdetail.ID, Empdetail.EmpCode, Empdetail.EmpName,Empdetail.DOJ,"+
"Department.ID, Department.DeptName, Country.CoName, State.SName, City.CiName, Qualification.QName from "+
"Empdetail JOIN Department on Empdetail.DepartmentID=Department.ID JOIN Country on Empdetail.CountryID=Country.ID"+
" JOIN State on Empdetail.StateID=State.ID JOIN City on Empdetail.CityID=City.ID"+
" JOIN Qualification on Empdetail.QualificationID=Qualification.ID;";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
protected void AddNewEmployee(object sender, EventArgs e)
{
string ID = ((TextBox)GridView1.FooterRow.FindControl("txtID")).Text;
string EmpCode = ((TextBox)GridView1.FooterRow.FindControl("txtEmpCode")).Text;
string Company = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
/*cmd.CommandText = "insert into Empdetail(EmpCode, CompanyName) " +
"values(#CustomerID, #ContactName, #CompanyName);" +
"select CustomerID,ContactName,CompanyName from customers";
cmd.Parameters.Add("#CustomerID", SqlDbType.VarChar).Value = CustomerID;
cmd.Parameters.Add("#ContactName", SqlDbType.VarChar).Value = Name;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Company;*/
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
Note:- I have searched extensively and on multiple sites so I would really appreciate it if you can tell me the exact issue instead of navigating me to a link. I am new to the concept of Gridview so please critique the code with an open mind. Thanks in advance

In the aspx file I'd drop data sources for each dropdown, SqlDataSource for example. In the markup you can fully define each DDL and every row uses the same single instance of the datasource. On editing you need only capture the selected value to update.
So...the DataSource for the Department example...
. . .
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
SelectCommand="SELECT ID,DeptName FROM Department"
EnableCaching="True">
</asp:SqlDataSource>
Then in the GridView Template for Department...
<EditItemTemplate>
<asp:DropDownList ID = "Depddl" runat="server" Width="100px" >
DataSourceID="SqlDataSource1"
DataTextField="DeptName"
DataValueField="ID"
</asp:DropDownList>
</EditItemTemplate>
And in the code behind you can optionally select the current value for the DDL from a current value...or not...up to you.
protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e )
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
if ( e.Row.RowState.HasFlag( DataControlRowState.Edit ) )
{
DataRowView drv = (DataRowView) e.Row.DataItem;
DropDownList ddl = (DropDownList) e.Row.FindControl( "DropDownList1" );
ddl.SelectedValue = ((int) drv[ "ID" ]).ToString();
}
}
}

After commenting several segments of the code I realized that the issue was with the "OnRowDataBound" function.
Commenting these lines made the update button fire again:-
string Department = (e.Row.FindControl("lblDepartment") as Label).Text;
Depddl.Items.FindByValue(Department).Selected = true;
What I could gather from this is that I cannot access an Item template control that way. Commenting the lines made the page run smoothly. However it was at the cost of losing the functionality of auto-selecting the original data value. I would like to implement this and will post an update as soon as I can achieve this.

Related

Filtering on asp gridview headers using dropdowns on multiple columns

So I tried to added multiple filters for the gridview and I populated the dropdowns with the distinct datas of the column, but it gives me an exception, System.ArgumentException: Parameter 'siteValue' not found in the collection. I've added the mysql stored procedure along with the below code.
<asp:GridView ID="gdvTM" runat="server" AutoGenerateColumns="False" AllowPaging="true" OnPageIndexChanging="gdvTM_PageIndexChanging" DataKeyNames="ID" PageSize="10" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc" >
<Columns >
<asp:TemplateField HeaderText="Agent login">
<ItemTemplate>
<asp:Label ID="lbllogin" runat="server" Text='<%# Eval("agentlogin") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<HeaderTemplate>
Site:
<asp:DropDownList ID="ddlgvsite" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblsite" runat="server" Text='<%# Eval("site") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Skill:
<asp:DropDownList ID="ddlgvskill" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblskill" runat="server" Text='<%# Eval("skill") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift">
<ItemTemplate>
<asp:Label ID="lblshift" runat="server" Text='<%# Eval("shift") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TM">
<ItemTemplate>
<asp:Label ID="lbltm" runat="server" Text='<%# Eval("tm") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GrpM">
<ItemTemplate>
<asp:Label ID="lblGrpM" runat="server" Text='<%# Eval("grpM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OpsM">
<ItemTemplate>
<asp:Label ID="lblOpsM" runat="server" Text='<%# Eval("opsM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Leave type">
<ItemTemplate>
<asp:Label ID="lbltype" runat="server" Text='<%# Eval("leavetype") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate >
<asp:Label ID="lbldate" runat="server" Text='<%# Eval("date", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<asp:Label ID="lbltime" runat="server" Text='<%# Eval("time") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason" ControlStyle-Width="300px">
<ItemTemplate>
<asp:Label ID="lblreason" runat="server" Text='<%# Eval("reason") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below would be the server side codes
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindDropDownList()
{
TableCell cells = gdvTM.HeaderRow.Cells[0];
PopulateDropDown((cells.FindControl("ddlgvsite") as DropDownList), (cells.FindControl("lblsite") as Label).Text);
PopulateDropDown((cells.FindControl("ddlgvskill") as DropDownList), (cells.FindControl("lblskill") as Label).Text);
}
private void PopulateDropDown(DropDownList ddl, string columnName)
{
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please Select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetApprovedData");
cmd.CommandType = CommandType.StoredProcedure;
if (ViewState["Site"] != null && ViewState["Site"].ToString() != "0")
{
cmd.Parameters.AddWithValue("#siteValue", ViewState["Site"].ToString());
}
if (ViewState["Skill"] != null && ViewState["Skill"].ToString() != "0")
{
cmd.Parameters.AddWithValue("#skillValue", ViewState["Skill"].ToString());
}
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Site"] != null ? (string)ViewState["Site"] : string.Empty, cell.FindControl("ddlgvsite") as DropDownList);
setDropdownselectedItem(ViewState["Skill"] != null ? (string)ViewState["Skill"] : string.Empty, cell.FindControl("ddlgvskill") as DropDownList);
}
private void setDropdownselectedItem(string selectedvalue, DropDownList ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
DropDownList dropdown = (DropDownList)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlgvsite":
ViewState["Site"] = selectedValue;
break;
case "ddlgvskill":
ViewState["Skill"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT " + columnName + " FROM approved WHERE " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
protected void gdvTM_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gdvTM.PageIndex = e.NewPageIndex;
this.BindGrid();
}
Below would be the MySql stored procedure
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData`
(in siteValue varchar(45), in skillValue varchar(100))
BEGIN
select *
from approved
where site = siteValue or siteValue is null and
skill = skillValue or skillValue is null;
END
Please let me know what I'm doing wrong. Thanks in advance....
1) You have to changes your stored procedure like
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData`(in siteValue varchar(45),
in skillValue varchar(100))
BEGIN
IF siteValue IS NULL and skillValue IS NULL THEN
select * from approved;
ELSEIF siteValue IS NULL and skillValue IS NOT NULL THEN
select * from approved where skill = skillValue;
ELSEIF siteValue IS NOT NULL and skillValue IS NULL THEN
select * from approved where site = siteValue;
ELSE
select * from approved where site = siteValue and skill = skillValue;
END IF;
END
2) In your BindGrid function make the changes below
private void BindGrid()
{
//Your rest of code is same here
string siteValue = null;
string skillValue = null;
if (ViewState["Site"] != null && ViewState["Site"].ToString() != "0")
{
siteValue = ViewState["Site"].ToString();
}
if (ViewState["Skill"] != null && ViewState["Skill"].ToString() != "0")
{
skillValue = ViewState["Skill"].ToString();
}
cmd.Parameters.AddWithValue("siteValue", siteValue);
cmd.Parameters.AddWithValue("skillValue", skillValue);
//Your rest of code is same here
}

how to CRUD operation in gridview using 3 tier

I am using n tier architecture
Here is my aspx.cs code
using System;
using System.Web.UI;
using BAL;
using System.Web.UI.WebControls;
namespace GridViewThreeTierApplication
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
var dataSource = new DAL.dal().GetAllCustomers();
if (dataSource != null)
{
GridView1.DataSource = dataSource;
GridView1.DataBind();
}
}
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Control control = e.Row.Cells[0].Controls[0];
if (control is LinkButton)
{
int num = Convert.ToInt32(e.Row.RowIndex);
bal.DeleteCustomers(num);
}
}
}
}
}
here is my markup
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="GridViewThreeTierApplication.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" OnDataBound="GridView1_DataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="LinkButton1" runat="server" Text="Update" CommandName="Update" CausesValidation="true" />
<asp:Button ID="LinkButton2" runat="server" Text="Cancel" CausesValidation="false" CommandName="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CustomerID" SortExpression="CustomerID">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("CustomerID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("CustomerID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="InsertBtn" runat="server" Text="Insert" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName" SortExpression="LastName">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFiname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email" SortExpression="Email">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PhoneNumber" SortExpression="PhoneNumber">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("PhoneNumber") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PhoneNumber") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFirname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</div>
</form>
</body>
</html>
here is my data access layer
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
namespace DAL
{
public class dal
{
public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int PhoneNumber { get; set; }
}
public List<Customer> GetAllCustomers()
{
List<Customer> listCustomers = new List<Customer>();
string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Select * from Customer", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Customer Customer = new Customer();
Customer.CustomerID = Convert.ToInt32(rdr["CustomerID"]);
Customer.FirstName = rdr["FirstName"].ToString();
Customer.LastName = rdr["LastName"].ToString();
Customer.Email = rdr["Email"].ToString();
Customer.PhoneNumber = Convert.ToInt32(rdr["PhoneNumber"]);
listCustomers.Add(Customer);
}
}
return listCustomers;
}
}
}
here is my business object
using System.Configuration;
using System.Data.SqlClient;
namespace BAL
{
public class bal
{
protected void GetALLCustomer()
{
}
public static void DeleteCustomers(int CustomerID)
{
string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand ("Delete from Customer where CustomerID = #CustomerID", con);
SqlParameter param = new SqlParameter("#CustomerId", CustomerID);
cmd.Parameters.Add(param);
con.Open();
cmd.ExecuteNonQuery();
}
}
public static int InsertCustomers(string FirstName, string LastName, string Email, int PhoneNumber)
{
string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string updateQuery = "Insert into Customers (FirstName, LastName, Email,PhoneNumber)" +
" values (#FirstName, #LastName, #Email,#PhoneNumber)";
SqlCommand cmd = new SqlCommand(updateQuery, con);
SqlParameter paramFirstName = new SqlParameter("#FirstName", FirstName);
cmd.Parameters.Add(paramFirstName);
SqlParameter paramLastName = new SqlParameter("#LastName", LastName);
cmd.Parameters.Add(paramLastName);
SqlParameter paramEmail = new SqlParameter("#Email", Email);
cmd.Parameters.Add(paramEmail);
SqlParameter paramPhoneNumber = new SqlParameter("#PhoneNumber", PhoneNumber);
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
}
I am able to perform select query .
I can not perform Create ,Delete or Update .
It seems like the phone number parameter is not on the cmd command
Here is how i got it to work
1) First i deleted event GridView1_DataBound
Delete "CommandField" column from GridView1 (markup)
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
2) insert this markup in its place
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbEdit" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="EditRow" ForeColor="#8C4510" runat="server">Edit</asp:LinkButton>
<asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false">Delete</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lbUpdate" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="UpdateRow" ForeColor="#8C4510" runat="server">Update</asp:LinkButton>
<asp:LinkButton ID="lbCancel" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="CancelUpdate" ForeColor="#8C4510" runat="server" CausesValidation="false">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
3) insert this FooterTemplate of EmployeeId
Insert
4) Now generate GridView1_RowCommand() event handler method.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
GridView1.EditIndex = rowIndex;
BindGrid();
}
else if (e.CommandName == "DeleteRow")
{
BAL.bal.DeleteCustomers(Convert.ToInt32(e.CommandArgument));
BindGrid();
}
else if (e.CommandName == "CancelUpdate")
{
GridView1.EditIndex = -1;
BindGrid();
}
else if (e.CommandName == "UpdateRow")
{
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int CustomerId = Convert.ToInt32(e.CommandArgument);
string Name = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox1")).Text;
string Gender = ((DropDownList)GridView1.Rows[rowIndex].FindControl("DropDownList1")).SelectedValue;
string City = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox3")).Text;
BAL.bal.UpdateCustomers(CustomerId, Name, Gender, City);
GridView1.EditIndex = -1;
BindGrid();
}
else if (e.CommandName == "InsertRow")
{
string Name = ((TextBox)GridView1.FooterRow.FindControl("txtName")).Text;
string Gender = ((DropDownList)GridView1.FooterRow.FindControl("ddlGender")).SelectedValue;
string City = ((TextBox)GridView1.FooterRow.FindControl("txtCity")).Text;
BAL.bal.InsertCustomers(name, gender, city);
BindGrid();
}
}
6) Correct insertCustomer Method
public static int InsertCustomers(string Name, string Gender, string City)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string updateQuery = "Insert into tblEmployee (Name, Gender, City)" +
" values (#Name, #Gender, #City)";
SqlCommand cmd = new SqlCommand(updateQuery, con);
SqlParameter paramName = new SqlParameter("#Name", Name);
cmd.Parameters.Add(paramName);
SqlParameter paramGender = new SqlParameter("#Gender", Gender);
cmd.Parameters.Add(paramGender);
SqlParameter paramCity = new SqlParameter("#City", City);
cmd.Parameters.Add(paramCity);
con.Open();
return cmd.ExecuteNonQuery();
}
}
If you want to show a confirmation dialog box, before a row is deleted, include javascript confirm() function, using "OnClientClick" attribute of LinkButton "lbDelete".
<asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this row');">Delete</asp:LinkButton>

displaying read more option when user enters large amount of data in richtextbox

I have a richtextbox and a gridview.
When I enter the data into the richtextbox, it should be displayed in a gridview and saved in database.
Now my requirement is that, if i am entering a paragraph or a large amount of data I should display a "readmore" button, that when clicked, display the complete data.
<%# Register Assembly="FreeTextBox" Namespace="FreeTextBoxControls" TagPrefix="FTB" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Richtextbox Sample</title>
<script type="text/javascript">
function validate() {
var doc = document.getElementById('FreeTextBox1');
if (doc.value.length == 0) {
alert('Please Enter data in Richtextbox');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<FTB:FreeTextBox ID="FreeTextBox1" runat="server">
</FTB:FreeTextBox>
</td>
<td valign="top">
<asp:GridView runat="server" ID="gvdetails" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="RichtextBoxData">
<ItemTemplate>
<asp:Label ID="lbltxt" runat="server" Text='<%#Bind("RichtextData") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return validate()"
Text="Submit" onclick="btnSubmit_Click" />
<br />
<asp:Label ID="lbltxt" runat="server"/>
</form>
</body>
</html>
c# code-
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGridview();
}
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select RichTextData from RichTextBoxData", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into RichTextBoxData(RichTextData) values(#Richtextbox)", con);
cmd.Parameters.AddWithValue("#Richtextbox", FreeTextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
FreeTextBox1.Text = "";
BindGridview();
}
first in your select query add id of your text(your primary key of table RichTextBoxData)
and in gridview make it,s visible =false like this
<asp:TemplateField HeaderText="id" InsertVisible="False" Visible="False">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
and then
protected void gvdetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lb =e.Row.FindControl("lbltxt") as Label;
if (lb.Text.Length > 15)//any length u want
{
DataRow drv = ((DataRowView)e.Row.DataItem).Row;
int tempID = Convert.ToInt32(drv["id"].ToString());
HyperLink hp = new HyperLink();
hp.Text = "read more";
hp.NavigateUrl = "~/mydetails.aspx?id=" + tempID;
e.Row.Cells[1].Controls.Add(hp);
lb.Text = lb.Text.Substring(0, 15);
}
}
}
and on page_load of mydetails.aspx make
query to select RichTextData where id=request.querystring["id"]

Concatenating more than one columns in SQL Server

I have a query in which I have to add more than one column.
Result of query is stored DataTable and binding it to Repeater. But the problem is DataTable shows the columns name and not the names I specified in query.
HTML (Persons.aspx):
<body>
<form id="form1" runat="server">
<h1><b>Persons</b></h1>
<div style="float:right">
<asp:LinkButton ID="lnkAdd" runat="server" Text="Add" Style="margin-right:100px"></asp:LinkButton>
</div>
<br />
<br />
<asp:Repeater ID="rptPersons" runat="server">
<ItemTemplate>
<div style="float: left">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Pic") %>' Width="100px" Height="100px" />
</div>
<div style="float:left;margin-left:10px;">
<asp:Label ID="lblName" runat="server" Text='<%# Eval("PersonName") %>'></asp:Label><br />
<asp:Label ID="lblPost" runat="server" Text='<%# Eval("Post") %>'></asp:Label><br />
<asp:Label ID="lblLocation" runat="server" Text='<%# Eval("Location") %>'></asp:Label><br />
<%--<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age") %>'></asp:Label><br />--%>
</div>
</ItemTemplate>
<SeparatorTemplate>
<div style="margin-left:20px"></div>
</SeparatorTemplate>
</asp:Repeater>
</form>
</body>
Stored procedure:
select
FirstName as PersonName,
ISNULL(Designation,'') + ',' + ISNULL(Organization,'') as Post,
ISNULL(tblPersons.City,'') + ',' + ISNULL(tblPersons.State,'') as Location,
GETDATE() - tblPersons.dob + '( DoJ :' + '' + ISNULL(tblPersons.doj,'') as Age,
tblPersons.photo_name as Pic
from
tblpersons
Logic class:
public class PersonsLogic
{
public DataTable GetPersons()
{
string Connection = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using(SqlConnection con = new SqlConnection(Connection))
{
SqlCommand cmd = new SqlCommand("spGetPersons", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
}
}
Persons.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Persons objPerson = new Persons();
PersonsLogic objLogic = new PersonsLogic();
DataTable dt = objLogic.GetPersons();
if (dt.Rows.Count > 0)
{
rptPersons.DataSource = dt;
rptPersons.DataBind();
}
else
{
}
}

Populate DropDownList inside template field in GridView with data from CodeBehind

I have created this gridview .This is my code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList dropdownnop = (e.Row.FindControl("dropdownnop") as DropDownList);
dropdownnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
dropdownnop.DataTextField = "DESC";
dropdownnop.DataValueField = "DESC";
dropdownnop.DataBind();
// Select the payment nature in DropDownList
string nop = (e.Row.FindControl("NOP") as Label).Text;
dropdownnop.Items.FindByValue(nop).Selected = true;
}
here's my html gridview code
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="Black" BorderStyle="Solid" Font-Bold="True" Font-Italic="False" Font-Size="Small" Height="72px" style="margin-left: 41px; margin-top: 108px" Width="783px" DataKeyNames="ID" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" AutoGenerateColumns="False" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="OnRowDataBound">
<AlternatingRowStyle BackColor="#FFFFCC" BorderColor="#FF9900" Wrap="False" />
<Columns>
<asp:TemplateField HeaderText="TASK ID" SortExpression="TASK ID" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="TASKID" runat="server" Text='<%#Eval("[TASK ID]") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NATURE OF PAYMENT" SortExpression="NATURE OF PAYMENT" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="NOP" runat="server" Text='<%#Eval("[NATURE OF PAYMENT]") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownnop"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DESC" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DESC" Text='<%#Eval("[DESC]") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID ="DESC" runat="server" Text='<%#Eval("[DESC]") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="REQUIREDFIELDVALIDATORDESC" runat="server" ControlToValidate="DESC" ErrorMessage="FIELD CANNOT BE EMPTY"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FREQUENCY" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="FREQUENCY" Text='<%#Eval("FREQUENCY") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownfreq"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DUE DATE OF PAYMENT" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DDOP" Text='<%#Eval("PREALERT1") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownddop"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DUE DATE OF SUBMISSION OF RETURN" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DDOSOR" Text='<%#Eval("PREALERT2") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownddosor"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OWNER" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="OWNER" Text='<%#Eval("OWNER") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownowner"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="VERIFICATION OWNER" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="VO" Text='<%#Eval("[VERIFICATION OWNER]") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownvo"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="STATUS" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="STATUS" Text='<%#Eval("STATUS") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat ="server" ID="dropdownstatus">
<asp:ListItem Text="Active" Value="1"></asp:ListItem>
<asp:ListItem Text="Inactive" Value="0"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false" HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" ID="ID" Text='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="4" />
</asp:GridView>
So, my problem here is that Iam able to edit is using the edit events but I am not able to
populate the dropdown inside the gridview, whereas Iam able to do the same outside the GridView.
Here's my full codebehind
{
Comp obj6 = new Comp();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate gridview
TextBox2.Focus();
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.PopulateGrid(GridView1, selectquery);
{
// populate dropdownlist for prealert 1
for (int i = 0; i <= 30; i++)
{
DropDownList3.Items.Insert(i, new ListItem((i + 1).ToString(), (i + 1).ToString()));
}
DropDownList3.DataBind();
}
{
// populate dropdown list for prealert 2
for (int j = 0; j <= 30; j++)
{
DropDownList4.Items.Insert(j, new ListItem((j + 1).ToString(), (j + 1).ToString()));
}
DropDownList4.DataBind();
}
{
//populate dropdown for Nature of Payment
string query = "select * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';";
string columnname = "DESC";
string datavaluefield = "DESC";
obj6.PopulateCombo(DropDownList1, query, columnname, datavaluefield);
}
{
//populate dropdown for frequency
string query1 = "select * from Compliance_Tracker.dbo.frequencyMaster where STATUS='1';";
string columnname1 = "DESC";
string datavaluefield1 = "DESC";
obj6.PopulateCombo(DropDownList2, query1, columnname1, datavaluefield1);
}
{
//populate dropdown for owner
string query2 = "select * from Compliance_Tracker.dbo.ownerMaster where STATUS='1';";
string columnname2 = "NAME";
string datavaluefield2 = "NAME";
obj6.PopulateCombo(DropDownList5, query2, columnname2, datavaluefield2);
}
{
//populate dropdown for owner verification
string query3 = "select * from Compliance_Tracker.dbo.verificationMaster where STATUS='1'";
string columnname3 = "NAME";
string datavaluefield3 = "NAME";
obj6.PopulateCombo(DropDownList6, query3, columnname3, datavaluefield3);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string query = "insert into Compliance_Tracker.dbo.tasklistManager([NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],STATUS)values('" + DropDownList1.SelectedItem.Text + "','" + TextBox2.Text + "','" + DropDownList2.SelectedItem.Text + "','" + DropDownList3.SelectedItem.Text + "','" + DropDownList4.SelectedItem.Text + "','" + DropDownList5.SelectedItem.Text + "','" + DropDownList6.SelectedItem.Text + "','" + DropDownList7.SelectedValue + "');";
obj6.ExecuteScalar(query);
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.PopulateGrid(GridView1, selectquery);
TextBox2.Text = string.Empty;
DropDownList7.SelectedItem.Text = "Active";
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string query = "delete Compliance_Tracker.dbo.tasklistManager where Compliance_Tracker.dbo.tasklistManager.ID = " + ID;
string populatequery = query + ";select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.BindGridData(populatequery, GridView1);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList dropdownnop = (e.Row.FindControl("dropdownnop") as DropDownList);
dropdownnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
dropdownnop.DataTextField = "DESC";
dropdownnop.DataValueField = "DESC";
dropdownnop.DataBind();
// Select the payment nature in DropDownList
string nop = (e.Row.FindControl("NOP") as Label).Text;
dropdownnop.Items.FindByValue(nop).Selected = true;
}
}
And here's the fetchdata code
public DataTable Fetchdata(string strSQL)
{
SqlDataAdapter DAdpt = new SqlDataAdapter();
DataSet DSet = new DataSet();
try
{
if (Conn.State == ConnectionState.Closed)
Conn.Open();
DAdpt = new SqlDataAdapter(strSQL, Conn);
DAdpt.Fill(DSet);
return DSet.Tables[0];
}
catch (Exception Ex)
{
return null;
throw new Exception(Ex.Message);
}
finally
{
DAdpt.Dispose();
DSet.Dispose();
Conn.Close();
}
}
Must be some problem with find control code. Try the one I have using in the code given below :
protected void GrdPDataEdit_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Replace your find corntrol code with this
DropDownList drpnop = (DropDownList)e.Row.FindControl("dropdownnop");
if (drpnop != null)
{
drpnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
drpnop.DataTextField = "DESC";
drpnop.DataValueField = "DESC";
drpnop.DataBind();
}
}
}
You can't directly access the DropDownList inside of the GridView while the gridview is being generated. What you'll have to do is to use the GridView OnRowCreated event and populate the dropdown that way. I don't have any sample code handy, but there are a ton of references on the internet.
Most of your code is usable, but you'll need to move a few things around.
Basically you'll need to create an event for OnRowCreated and then - this is the key part - use the FindControl method to find the DropDownList and finally insert the items into the DDL.
Clarification: I thought your code in the OnLoad was trying to populate the DDL and I didn't see the code box scrolled down. Looks like your code is solid, I think you just need to switch from OnRowBinding to OnRowCreated

Categories