I have created gridview with paging and search a data within gridview.I have number of data and number of page if u filter data in gridview it successfully display result with paging. After display i will click on next page because gridview will display only 10 records per page but i have more than 10 records which i have filtered so it will display page wise. Then when i click next page gridview will loads whole data from database and display but i want display only filtered record while searching data.
the aspx code is below
<asp:Button ID="Search" Text="Search" runat="server" CssClass="searchbtn" OnClick="Search_Click" />
<asp:GridView ID="gvEdit" runat="server" AutoGenerateColumns="False" DataKeyNames="slno" OnRowCreated="gvEdit_RowCreated" OnPageIndexChanging="gvEdit_PageIndexChanging" Width="100%" AllowPaging="True" PageSize="10" OnRowCommand="gvEdit_RowCommand">
<HeaderStyle HorizontalAlign="Center" BackColor="#2D96CE" ForeColor="White" />
<AlternatingRowStyle BackColor="#D4EFFD" />
<PagerSettings Position="Top" />
<PagerStyle Height="8px" HorizontalAlign="Center" />
<PagerTemplate>
<table align="center" style="width: 100%;" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="center" style="width: 60%;">
<table align="center" width="50%">
<tr>
<td>
<asp:ImageButton ToolTip="First Page" CommandName="Page" CommandArgument="First" runat="server" ID="ImgeBtnFirst" ImageUrl="../Images/First.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Previous Page" CommandName="Page" CommandArgument="Prev" runat="server" ID="ImgbtnPrevious" ImageUrl="../Images/Previous.jpg" />
</td>
<td style=" width: 8%;">
<asp:Label ID="lblpageindx" CssClass="labelBold" Text="Page : " runat="server"></asp:Label>
<asp:DropDownList ToolTip="Goto Page" ID="ddlPageSelector" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageSelector_SelectedIndexChanged" CssClass="combo_common_nowidth hide">
</asp:DropDownList>
</td>
<td>
<asp:ImageButton ToolTip="Next Page" CommandName="Page" CommandArgument="Next" runat="server" ID="ImgbtnNext" ImageUrl="../Images/Next.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Last Page" CommandName="Page" CommandArgument="Last" runat="server" ID="ImgbtnLast" ImageUrl="../Images/Last.jpg" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</PagerTemplate>
<Columns>
<asp:BoundField DataField="form_key" HeaderText="FilingID" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="business_key" HeaderText="BusinessKey" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="ref_no" HeaderText="Reference" HeaderStyle-Width="200px" />
<asp:BoundField DataField="fum" HeaderText="Period" HeaderStyle-Width="11%" />
<asp:BoundField DataField="filing_type" HeaderText="Filing Type" HeaderStyle-Width="19%" />
<asp:BoundField DataField="business_name" HeaderText="Business" HeaderStyle-Width="13%" />
<asp:BoundField DataField="filing_status" HeaderText="Status" HeaderStyle-Width="200px" />
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="lnkBtnViewDetails_Click" Text='<%#Eval("form_details")%>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="" HeaderText="Schedule1" ItemStyle-Width="6.9%">
<ItemTemplate>
<a href="Schedule12290.aspx?key=<%#Eval("form_key") %>" target="_blank">
<img src="<%#Eval("schedule1") %>" alt="" />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Copy">
<ItemTemplate>
<asp:ImageButton ID="lnkDuplicate" runat="server"
ImageUrl="~/Images/grid/file_duplicate 35x35.png" OnClick="lnkbtnDuplicate_Click" ToolTip="Edit" CssClass='<%#Eval("duplicate") %>' OnClientClick="javascript:return confirm('Are you sure you want to copy from previous years filing?');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="lnkBtnContinue" runat="server"
ImageUrl="~/Images/grid/edit3.png" OnClick="imgBtnContinue_Click" ToolTip="Edit" CssClass='<%# Eval("continue")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDel" runat="server"
ImageUrl="~/Images/grid/delBlue.png" OnClick="imgBtnDelete_Click" ToolTip="Delete" CssClass='<%#Eval("delete") %>' OnClientClick="javascript:return confirm('Do you want to delete this file permanently?');" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and aspx.cs code is below
protected void Search_Click(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
try
{
if (txtsearch.Text != "")
{
if (ViewState["data"] != null)
{
DataTable dt = (DataTable)ViewState["data"];
DataView dv = new DataView(dt);
dv.RowFilter = "ref_no Like '%" + txtsearch.Text + "%' OR fum Like '%" + txtsearch.Text + "%' OR filing_type Like '%" + txtsearch.Text + "%'OR business_name Like '%" + txtsearch.Text + "%'OR filing_status Like '%" + txtsearch.Text + "%'";
ViewState["filter"] = dv;
gvEdit.DataSource = dv;
gvEdit.DataBind();
//gvformlist.DataSource = dv;
//gvformlist.DataBind();
}
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
protected void Reset_Click(object sender, EventArgs e)
{
txtsearch.Text = "";
gvEdit.DataSource = ViewState["data"];
gvEdit.DataBind();
//gvformlist.DataSource = ViewState["data"];
//gvformlist.DataBind();
}
protected void gvformlist_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//gvEdit.PageIndex = e.NewPageIndex;
//gvformlist.PageIndex = e.NewPageIndex;
LoadFormList();
}
protected void gvformlist_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow pagerRow = gvEdit.TopPagerRow;
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (e.Row.RowType == DataControlRowType.Pager)
{
pageLabel.Text = "Page " + (gvEdit.PageIndex + 1) + " of " + gvEdit.PageCount;
}
}
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page, string DDlPager)
{
// to Get No of pages and Page Navigation
int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
ImageButton btnFirst = (ImageButton)gvPagerRow.FindControl("ImgeBtnFirst");
ImageButton btnPrevious = (ImageButton)gvPagerRow.FindControl("ImgbtnPrevious");
ImageButton btnNext = (ImageButton)gvPagerRow.FindControl("ImgbtnNext");
ImageButton btnLast = (ImageButton)gvPagerRow.FindControl("ImgbtnLast");
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl(DDlPager);
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
string strPgeIndx = Convert.ToString(gridView.PageIndex + 1) + " of "
+ gridView.PageCount.ToString();
Label lblpageindx = (Label)gvPagerRow.FindControl("lblpageindx");
lblpageindx.Text += strPgeIndx;
}
protected void ddlPageSelector_SelectedIndexChanged(object sender, EventArgs e)
{
gvEdit.PageIndex = ((DropDownList)sender).SelectedIndex;
LoadFormList();
}
protected void gvEdit_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(gvEdit, e.Row, this, "ddlPageSelector");
}
}
protected void gvEdit_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
I have changed code in gvEdit_PageIndexChanging as per someone suggestion code is below
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
if (ViewState["filter"] != null)
{
gvEdit.PageIndex = e.NewPageIndex;
gvEdit.DataSource = ViewState["filter"];
gvEdit.DataBind();
}
else
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
after that i run the code and i am getting error
error is System.Runtime.Serialization.SerializationException: Type 'System.Data.DataView' in Assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
According to your question I try to give an answer. If you find my answer useful then mark is as answer or vote it up.
What I have done in below code is when user click on search button without input any student name it shows per page 10 records of all students and if you search by name it shows only specific students with paging. In below code I use a stored procedure and in that I put three parameters such as following:
#startRowIndex int
#pageSize int
#studentname varchar(50) = NULL
Default.aspx markup:
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<table>
<tr>
<td>Gridview Pagging</td>
</tr>
<tr>
<td>
<asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSearch" Text="Search" runat="server" OnClick="btnSearch_Click" />
</td>
</tr>
</table>
<div>
<asp:GridView ID="gv" runat="server" Width="100%" EmptyDataText="No Data Found!"
ShowFooter="False" AutoGenerateColumns="False" SkinID="WithOutPaging" GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="Studentname" HeaderText="Student Names"></asp:BoundField>
<asp:BoundField DataField="Studentage" HeaderText="Age"></asp:BoundField>
</Columns>
<EmptyDataRowStyle CssClass="emptyrow" />
<HeaderStyle CssClass="headerstyle2" />
<FooterStyle CssClass="footerstyle"></FooterStyle>
<EditRowStyle CssClass="editrowstyle"></EditRowStyle>
<SelectedRowStyle CssClass="selectedrowstyle"></SelectedRowStyle>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"></PagerStyle>
</asp:GridView>
</div>
<div style="margin-top: 20px; margin-bottom: 70px;" align="center">
<asp:Button ID="btnFirst" runat="server" Text="First" CommandName="First" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnPrevious" runat="server" Text="Previous" CommandName="Previous"
OnCommand="ChangePage" Visible="False" />
<asp:Button ID="btnNext" runat="server" Text="Next" CommandName="Next" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnLast" runat="server" Text="Last" CommandName="Last" OnCommand="ChangePage"
Visible="False" />
<br />
<br />
<asp:Label ID="lblPageText1" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> Page </asp:Label>
<asp:Label ID="lblCurrentPage" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
<asp:Label ID="lblPageText2" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> of </asp:Label>
<asp:Label ID="lbltotalPages" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Default.aspx.cs code:
#region "Declaration"
private int pageSize = 10;
SqlConnection con;
string conquery = "Data Source=.;Initial Catalog=GridviewPagging;User ID=sa;Password = 123";
#endregion
#region "Events"
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["startRowIndex"] = 0;
ViewState["currentPageNumber"] = 0;
}
}
protected void ChangePage(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "First":
ViewState["currentPageNumber"] = 1;
ViewState["startRowIndex"] = 0;
break;
case "Previous":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) - 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) - pageSize;
break;
case "Next":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) + 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) + pageSize;
break;
case "Last":
ViewState["startRowIndex"] = pageSize * (Int32.Parse(lbltotalPages.Text) - 1);
ViewState["currentPageNumber"] = lbltotalPages.Text;
break;
}
this.fillgridview();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
fillgridview();
}
#endregion
#region "Methods"
private DataSet ds(int RowIndex, int Pagesize, string studentname)
{
DataSet dataset;
try
{
con = new SqlConnection(conquery);
SqlCommand cmd = new SqlCommand("SP_GET_STUDENT_DATA", con);
cmd.Parameters.AddWithValue("#startRowIndex", RowIndex);
cmd.Parameters.AddWithValue("#pageSize", Pagesize);
cmd.Parameters.AddWithValue("#studentname", studentname);
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
dataset = new DataSet();
da.Fill(dataset);
}
return dataset;
}
catch (SqlException ex)
{
return dataset = null;
}
}
private void fillgridview()
{
DataSet newds = ds(Convert.ToInt32(ViewState["startRowIndex"].ToString()), pageSize, searchbox.Text.Trim());
if (newds.Tables.Count == 0)
{
return;
}
else
{
btnFirst.Visible = true;
btnPrevious.Visible = true;
btnNext.Visible = true;
btnLast.Visible = true;
lblCurrentPage.Visible = true;
lbltotalPages.Visible = true;
lblPageText1.Visible = true;
lblPageText2.Visible = true;
ViewState["TotalRows"] = newds.Tables[1].Rows[0][0];
newds.Tables[1].Rows.Clear();
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 0)
{
ViewState["currentPageNumber"] = 1;
}
setPages();
this.gv.Visible = true;
this.gv.DataSource = newds.Tables[0];
this.gv.DataBind();
}
}
private void setPages()
{
lbltotalPages.Text = "";
lblCurrentPage.Text = "";
try
{
lbltotalPages.Text = CalculateTotalPages(Convert.ToDouble(ViewState["TotalRows"])).ToString();
lblCurrentPage.Text = (ViewState["currentPageNumber"] == null ? "0" : ViewState["currentPageNumber"].ToString());
if (Int32.Parse(lblCurrentPage.Text) == 0 | Int32.Parse(lbltotalPages.Text) == 0)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
else
{
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 1)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
if (int.Parse(lbltotalPages.Text) > 0)
{
this.btnNext.Enabled = true;
this.btnLast.Enabled = true;
}
else
{
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
}
else
{
btnPrevious.Enabled = true;
btnFirst.Enabled = true;
}
if (Convert.ToInt32(ViewState["currentPageNumber"]) == int.Parse(lbltotalPages.Text))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
}
catch (Exception ex)
{
}
}
private int CalculateTotalPages(double totalrows)
{
return Convert.ToInt32(Math.Ceiling(totalrows / pageSize));
}
#endregion
first set enablepagingandcallback = false in gridview , then add
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = SqlDataSource1; //it is the datasource with filtered query which does the work
GridView1.DataBind();
}
Related
I am working in a ASP.NET project in an empty web application in C# and I have made a gridview with CRUD operations. But when I execute my project and click on the buttons I have made it takes me to the first row and I then have to scroll back down again. It is really annoying but I do not know why it does that. Even though I have used MaintainScrollPositionOnPostBack="true" it does not work. Is there anything I cad add to my code or something I have to be aware of?
Default.aspx
<%# Page Language="C#" MaintainScrollPositionOnPostBack="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestUsers.Default" %>
<link href="TestUsers.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
<link rel="stylesheet" href="TestUsers.css">
<link rel="shortcut icon" type="image/x-icon" href="~/orbitone.ico" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ESDTESTERS</title>
<%-- <meta http-equiv="refresh" content="20">--%>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<br /><br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Sing Out" />
<br /><br />
<asp:TextBox ID="TextBox1" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" Width="100px" />
<br />
</div>
<asp:GridView ID="gvTestUsers" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="tbl_users_key" ShowHeaderWhenEmpty="True" OnRowCommand="gvTestUsers_RowCommand" OnRowEditing="gvTestUsers_RowEditing" OnRowCancelingEdit="gvTestUsers_RowCancelingEdit"
OnRowDeleting="gvTestUsers_RowDeleting" OnRowUpdating="gvTestUsers_RowUpdating" HorizontalAlign="Center" OnPageIndexChanging="gvTestUsers_PageIndexChanged"
BackColor="#CCCCCC" BorderColor="#000000" BorderStyle="Solid" BorderWidth="3px" CellPadding="5" Width="1300px" CellSpacing="2" ForeColor="Black" PageSize="15" AllowPaging="True" >
<%--Theme Properties--%>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" Font-Size="Large" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
<Columns>
<asp:TemplateField HeaderText="tbl_users_key">
<ItemTemplate>
<asp:Label Text='<%# Eval("tbl_users_key") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtID" Text='<%# Eval("tbl_users_key") %>' runat="server" ReadOnly="true" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label Text='<%# Eval("Name") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" ReadOnly="True" Text='<%# Eval("Name") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNamefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CostCenter">
<ItemTemplate>
<asp:Label Text='<%# Eval("CostCenter") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCostCenter" ReadOnly="True" Text='<%# Eval("CostCenter") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCostCenterfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:Label Text='<%# Eval("Employee") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployee" ReadOnly="True" Text='<%# Eval("Employee") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FootPlate">
<ItemTemplate>
<asp:Label Text='<%# Eval("FootPlate") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFootPlate" Text='<%# Eval("FootPlate") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFootPlatefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="WirstCord">
<ItemTemplate>
<asp:Label Text='<%# Eval("WirstCord") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtWirstCord" Text='<%# Eval("WirstCord") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtWirstCordfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Excluded">
<ItemTemplate>
<asp:Label Text='<%# Eval("Excluded") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExcluded" Text='<%# Eval("Excluded") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExcludedfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:Label Text='<%# Eval("Comment") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtComment" Text='<%# Eval("Comment") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCommentfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/delete.png" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" ToolTip="Delete" Width="20px" Height="20px" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="~/GridImages/add.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<asp:Label ID="lblSuccessMessage" Text="" runat="server" ForeColor="Green" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
<br />
<asp:Label ID="lblErrorMessage" Text="" runat="server" ForeColor="Red" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
</div>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace TestUsers
{
public partial class Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGridView();
}
}
void PopulateGridView()
{
DataTable dtbl = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("Select * FROM TBL_USERS", sqlCon);
sqlDa.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
}
else
{
dtbl.Rows.Add(dtbl.NewRow());
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
gvTestUsers.Rows[0].Cells.Clear();
gvTestUsers.Rows[0].Cells.Add(new TableCell());
gvTestUsers.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count;
gvTestUsers.Rows[0].Cells[0].Text = "No Data Found.";
gvTestUsers.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
protected void gvTestUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("AddNew"))
{
int tbl_users_key = 0;
TextBox myTxt;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtNamefooter"));
string Name;
Name = myTxt.Text;
string CostCenter;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCostCenterfooter"));
CostCenter = myTxt.Text;
string Employee;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtEmployeefooter"));
Employee = myTxt.Text;
Boolean FootPlate;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtFootPlatefooter"));
FootPlate = Convert.ToBoolean(myTxt.Text);
Boolean WirstCord;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtWirstCordfooter"));
WirstCord = Convert.ToBoolean(myTxt.Text);
Boolean Excluded;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtExcludedfooter"));
Excluded = Convert.ToBoolean(myTxt.Text);
string Comment;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCommentfooter"));
Comment = myTxt.Text;
string sMsg;
sMsg = "";
bool btest = fcEditTBL_USERS(tbl_users_key, Name, CostCenter, Employee, FootPlate, WirstCord, Excluded, Comment, ref sMsg,0);
if (btest == false)
{
lblErrorMessage.Text = sMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = Name + " Was Added To Record.";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvTestUsers.EditIndex = e.NewEditIndex;
PopulateGridView();
}
protected void gvTestUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvTestUsers.EditIndex = -1;
PopulateGridView();
}
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, Convert.ToBoolean(dltFootPlate), Convert.ToBoolean(dltWirstCord), Convert.ToBoolean(dltExcluded), dltComment,ref dltsMsg,2);
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
gvTestUsers.EditIndex = -1;
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
public bool fcEditTBL_USERS
(int tbl_users_key, string Name, string CostCenter, string Employee, bool FootPlate, bool WirstCord, bool Excluded, string Comment, ref string sMsg, int iMode)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
try
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spEditTBL_USERS", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter returnParameter = sqlCmd.Parameters.Add(new SqlParameter("#RETURN_VALUE", DbType.Int32));
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCmd.Parameters.Add("#ID", SqlDbType.Int).Value=tbl_users_key ;
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value=Name;
sqlCmd.Parameters.Add("#CostCenter", SqlDbType.VarChar, 10).Value=CostCenter;
sqlCmd.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value=Employee;
sqlCmd.Parameters.Add("#FootPlate", SqlDbType.Bit).Value=FootPlate;
sqlCmd.Parameters.Add("#WirstCord", SqlDbType.Bit).Value=WirstCord;
sqlCmd.Parameters.Add("#Excluded", SqlDbType.Bit).Value=Excluded;
sqlCmd.Parameters.Add("#Comment", SqlDbType.VarChar, 255).Value=Comment;
sqlCmd.Parameters.Add("#MODE", SqlDbType.SmallInt).Value =iMode;
sqlCmd.Parameters.Add("#MSG", SqlDbType.NVarChar, 255).Value=sMsg;
sqlCmd.Parameters["#MSG"].Direction = ParameterDirection.Output;
sqlCmd.ExecuteNonQuery();
sMsg = sqlCmd.Parameters["#MSG"].Value.ToString();
int rtn = (int)sqlCmd.Parameters["#RETURN_VALUE"].Value;
if (rtn != 0)
{
return false;
}
sqlCmd.Dispose();
return true;
}
finally
{
}
}
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, Convert.ToBoolean(tmpFootPlate), Convert.ToBoolean(tmpWirstCord), Convert.ToBoolean(tmpExcluded), tmpComment,ref tmpsMsg,1);
//Reload Page
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_PageIndexChanged(object sender, GridViewPageEventArgs e)
{
gvTestUsers.PageIndex = e.NewPageIndex;
PopulateGridView();
}
protected void Button1_Click(object sender, EventArgs e)
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand (find,con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("LoginForm.aspx");
}
}
}
Thank you for the explanation. Please try setting gridview editindex before populating the gridview (after updating and deleting ) Hope this helps.
Working below code for me.
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, tmpFootPlate, tmpWirstCord, tmpExcluded, tmpComment, ref tmpsMsg, "Update");
//add this
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
And the row deleting below,
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, dltFootPlate, dltWirstCord,dltExcluded, dltComment, ref dltsMsg, "Delete");
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
I solved it by moving the SearchBox-Event code into my PopulateGridView.
So now the PopulateGridView looks like this:
void PopulateGridView()
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
And the Searchbox-Event:
protected void Button1_Click(object sender, EventArgs e)
{
PopulateGridView();
}
Else it would jump straight to Void PopulateGridView each time I would try to use an EDIT,CREATE or DELETE operation.
Im beginner for the ASP.NET ,Im develop the File Upload in Grid View with Ajax Modal Popup its working i can upload image and i can see uploaded image in uploaded folder, but i cant make uploaded image Path to grid view, can you please help me.
ASPX
<asp:UpdatePanel ID="UpdatePanelArt" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="table-responsive col-sm-12">
<asp:GridView ID="gvArticle" ShowHeaderWhenEmpty="True" ClientIDMode="AutoID" CssClass="table table-bordered table-condensed table-hover" AutoGenerateColumns="False" runat="server" AllowPaging="True" PageSize="15" OnRowDataBound="gvArticle_RowDataBound" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" OnRowUpdating="gvArticle_RowUpdating">
<%--<HeaderStyle BackColor="#3d4247" ForeColor="White" />--%>
<Columns>
<asp:TemplateField HeaderText="intArticleDetail" Visible="false">
<ItemTemplate>
<asp:Label ID="lblArticleDetailId" Width="2" Text='<%# Bind("intArticleDetailId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SectionID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblSectionId" Width="2" Text='<%# Bind("intSectionId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Section">
<ItemTemplate>
<asp:Label ID="lblSectionName" Width="100" Text='<%# Bind("strSectionName") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Compound">
<EditItemTemplate>
<asp:Label ID="lblItemTypeEdit" Width="50" Text='<%# Bind("strCompoundName") %>' lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlCompoundId" Width="200" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemTemplate>
<asp:TextBox ID="txtdecSectionWeighte" Width="100%" Text='<%# Bind("decSectionWeight") %>' lientIDMode="Static" runat="server"> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:TemplateField HeaderText="Messagers">
<ItemTemplate>
<asp:TextBox ID="txtMessage" Width="100%" Text='<%# Bind("intMessageId") %>' ClientIDMode="Static" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Messagers">
<EditItemTemplate>
<asp:Label ID="lblMessageId" Width="50" Text='<%# Bind("strMessage") %>' ClientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlMessage" Width="300" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<ItemTemplate>
<asp:Label ID="FilePath" Width="2" runat="server"></asp:Label>
</ItemTemplate>
<asp:TemplateField HeaderText="Images">
<ItemTemplate>
<%-- <asp:Image ID="Image1" ImageUrl='<%# Eval("StrImage") %>' runat="server" Height="100" />--%>
<%-- <asp:FileUpload runat="server" AutoPostBack="True" ID="uploadFImage" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>--%>
<asp:LinkButton ID="lnkUpload" runat="server" Text="Upload Resume" ></asp:LinkButton>
<%--Using ModalPopupExtender--%>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="lnkUpload"
PopupControlID="pnlUpload" BackgroundCssClass="ModalPopupBG" CancelControlID="btnCancel">
</asp:ModalPopupExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="btnViewFImage" Width="40" Height="40"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="gvArticle"/>
</Triggers>
</asp:UpdatePanel>
</div>
</div><asp:Panel ID="pnlUpload" runat="server" Width="450px" BackColor="#E39A19"
BorderColor="#C3680D" BorderStyle="Solid">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table style="width: 450px; margin: 0 auto">
<tr>
<td align="right" style="background-image: url('backTable.PNG')">
</td>
</tr>
<tr>
<td align="left">
<asp:FileUpload ID="flp_Resume" runat="server" Width="222px" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server"
ControlToValidate="flp_Resume" ErrorMessage="*"
ToolTip="Please Select a File to Upload."></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator5" runat="server"
ControlToValidate="flp_Resume" ErrorMessage="*"
ToolTip="Only txt,doc or docx files are Allowed"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+((.pdf)|(.doc)|(.txt)|(.docx))$"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="left">
<asp:Button ID="btnUpload" runat="server" Text="Upload" Width="80px"
onclick="btnUpload_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" Width="80px" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblError" runat="server" Font-Bold="True" Font-Names="Georgia"
ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload"/>
</Triggers>
cs
#region Detail Save1
private DataTable CreateDetailSave()
{
DataTable dtDetailSave1 = new DataTable();
DataColumn dc1;
dc1 = new DataColumn("intArticleDetailId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intSectionId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intCompoundId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("decSectionWeight");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intMessageId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("uploadFImage");
dtDetailSave1.Columns.Add(dc1);
foreach (GridViewRow row in gvArticle.Rows)
{
DataRow dr = dtDetailSave1.NewRow();
Label lblintArticleDetailId = (Label)row.FindControl("lblArticleDetailId");
Label lblSectionId = (Label)row.FindControl("lblSectionId");
DropDownList ddlCompound = (DropDownList)row.FindControl("ddlCompoundId");
TextBox txtdecSectionWeighte = (TextBox)row.FindControl("txtdecSectionWeighte");
DropDownList intMessage = (DropDownList)row.FindControl("ddlMessage");
FileUpload uploadFImage = (FileUpload)row.FindControl("uploadFImage");
dr["intArticleDetailId"] = CurrentMode == "Add" ? -1 : Convert.ToInt32(lblintArticleDetailId.Text);
dr["intSectionId"] = Convert.ToInt32(lblSectionId.Text);
dr["intCompoundId"] = ddlCompound.SelectedValue;
dr["decSectionWeight"] = txtdecSectionWeighte.Text.Trim() != "" ? Convert.ToDecimal(txtdecSectionWeighte.Text.Trim()) : 0;
dr["intMessageId"] = intMessage.SelectedValue;
dr["uploadFImage"] = uploadFImage.HasFile;
dtDetailSave1.Rows.Add(dr);
}
return dtDetailSave1;
}
#endregion
#region Save
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
if (FSaveConfirmation() == true)
{
string strArticleNo;
int intStatus = 8;
if (CurrentMode == "Add")
{
strArticleNo = "aaaaaaaa";
}
else
{
strArticleNo = txtArticleNo.Text.ToString();
}
DataTable dtDetailSave1 = CreateDetailSave();
string PageName = Path.GetFileNameWithoutExtension(Page.AppRelativeVirtualPath);
string Saved = clsArticle.saveArticleData(SelectedArticleId, strArticleNo, txtArticleDescription.Text.ToString(), txtRemarks.Text.ToString(), intStatus, 1, CurrentMode,
PageName, 16, dtDetailSave1);
if (Saved != "Error")
{
lblMsg.ForeColor = System.Drawing.Color.Green;
if (CurrentMode == "Add")
{
lblMsg.Text = "Record Saved Successfully";
txtArticleNo.Text = Saved.ToString();
}
else if (CurrentMode == "Modify")
{
lblMsg.Text = "Record Updated Successfully";
}
else if (CurrentMode == "Delete")
{
lblMsg.Text = "Record Deleted Successfully";
}
else if (CurrentMode == "Confirm")
{
lblMsg.Text = "Record Confirmed Successfully";
}
btnClear.Enabled = true;
btnSave.Enabled = true;
}
else if (Saved == "Error")
{
lblMsg.Text = "Article Saving Error";
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Save Confirmation
private bool FSaveConfirmation()
{
lblMsg.ForeColor = System.Drawing.Color.Red;
Boolean blnSaveCon = true;
//if (CurrentMode == "Add")
//{
if (txtArticleDescription.Text.ToString() == "")
{
lblMsg.Text = "Enter Article Description";
blnSaveCon = false;
goto end;
}
//}
end: { }
return blnSaveCon;
}
#endregion
#region Get controls in page
private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection) where T : Control
{
foreach (Control control in controlCollection)
{
if (control is T)
resultCollection.Add((T)control);
if (control.HasControls())
GetControlList(control.Controls, resultCollection);
}
}
#endregion
#region pageload
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ClearControls();
FillArticleDetails();
EnableControls(false);
Session["SearchPopup"] = false;
}
else
{
if (Session["SearchPopup"] != null)
{
SearchPopup = (bool)(Session["SearchPopup"]);
if (SearchPopup != false)
{
MyMPE.Show();
}
else
{
MyMPE.Hide();
}
}
vAdSearchParaList = new List<SearchParametors>();
}
}
#endregion
#region Advance Search
protected void btnAdSearchClose(object sender, ImageClickEventArgs e)
{
Session["SearchPopup"] = false;
Session["sSearchddlList"] = null;
GridView dtgResult = (GridView)ucDesignation.FindControl("ucgrdSearchConditions");
dtgResult.DataSource = null;
dtgResult.DataBind();
dtgAdSearchResult.DataSource = null;
dtgAdSearchResult.DataBind();
MyMPE.Hide();
}
#region Create Article table
private void createArticleDataTable()
{
if (dt.Columns.Count == 0)
{
dt.Columns.Add(new DataColumn("intArticleDetailId", typeof(int)));
dt.Columns.Add(new DataColumn("intSectionId", typeof(int)));
dt.Columns.Add(new DataColumn("strSectionName", typeof(string)));
dt.Columns.Add(new DataColumn("intCompoundId", typeof(string)));
dt.Columns.Add(new DataColumn("decSectionWeight", typeof(string)));
dt.Columns.Add(new DataColumn("intMessageId", typeof(string)));
dt.Columns.Add(new DataColumn("uploadFImage", typeof(string)));
}
gvArticle.DataSource = dt;
gvArticle.DataBind();
}
#endregion
#region Compound Grid - Add empty row
private void ArticleGridAddEmptyRow(int newId)
{
DataRow newDr = null;
newDr = dt.NewRow();
newDr["intArticleDetailId"] = 1;
newDr["intSectionId"] = 1;
newDr["strSectionName"] = "";
newDr["intCompoundId"] = "";
newDr["decSectionWeight"] = "";
newDr["intMessageId"] = "";
newDr["strImage"] = "";
dt.Rows.Add(newDr);
if (dtArticleDetails == null || dtArticleDetails.Rows.Count == 0)
{
dtArticleDetails = dt;
}
else
{
dtArticleDetails.Merge(dt);
gvArticle.DataSource = dt;
gvArticle.DataBind();
}
}
#endregion
private void FillArticleDetails()
{
DataSet dtCompoundData = clsArticle.GeArticleDetailData(SelectedArticleId);
if (dtCompoundData.Tables[0].Rows.Count > 0)
{
createArticleDataTable();
dt = dtCompoundData.Tables[0];
dtArticleDetails = dt;
gvArticle.DataSource = dtArticleDetails;
gvArticle.DataBind();
}
else
{
lblMsg.Text = "No Records Found";
}
}
protected void gvArticle_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
{
}
DataTable CompoundCode = clsArticle.CompoundDataForGrid("");
DropDownList ddlCompoundId = (DropDownList)e.Row.FindControl("ddlCompoundId");
if (ddlCompoundId != null)
{
ddlCompoundId.DataTextField = "Compound Code";
ddlCompoundId.DataValueField = "Compound Id";
ddlCompoundId.DataSource = CompoundCode;
ddlCompoundId.DataBind();
string country = (e.Row.FindControl("ddlCompoundId") as DropDownList).Text;
ddlCompoundId.Items.FindByValue(country).Selected = true;
}
DataTable MsgCode = clsArticle.MessageDataForGrid("");
DropDownList ddlMessage = (DropDownList)e.Row.FindControl("ddlMessage");
if (ddlMessage != null)
{
ddlMessage.DataTextField = "Message Name";
ddlMessage.DataValueField = "Message Id";
ddlMessage.DataSource = MsgCode;
ddlMessage.DataBind();
ddlMessage.Items.Insert(0, new ListItem("Please select"));
string country = (e.Row.FindControl("ddlMessage") as DropDownList).Text;
ddlMessage.Items.FindByValue(country).Selected = true;
}
//}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (flp_Resume.HasFile)
{
string fileName = Path.GetFileName(flp_Resume.PostedFile.FileName);
string fullpath = Path.GetFullPath(flp_Resume.PostedFile.FileName);
flp_Resume.PostedFile.SaveAs(Server.MapPath("~/Uploaded Images/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
else
{
lblError.Text = "Please Select a File";
return;
}
}
Hi I have a GridView control and in it a TextBox control inside an EditItemTemplate Field.
Now I need to change the textbox text when the user enters the edit mode.
When I run the program the textbox will take the value of the label that was in the ItemTemplate and I cant access the textbox.
.aspx:
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False"
ShowHeader="False" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" OnRowCancelingEdit="GridView1_Cancel"
onrowupdating="GridView1_RowUpdating" onrowdeleting="GridView1_RowDeleting"
onrowdatabound="GridView1_RowDataBound" DataKeyNames="TweetID">
<Columns>
<asp:TemplateField HeaderText="ProfilePicture">
<ItemTemplate>
<asp:ImageButton ID="ProfileImage" runat="server" CommandName="Redirect"
CommandArgument='<%# Container.DataItemIndex %>' Height="40px" Width="40px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FullName">
<ItemTemplate>
<asp:label ID="FullNameLabel" runat="server" text='<%#Eval("FullName") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label ID="UserNameLabel" runat="server" Text='<%#Eval("UserName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tweet">
<ItemTemplate>
<%--<asp:Label ID="TweetLabel" runat="server" Text='<%#Eval("TweetText") %>'></asp:Label>--%>
<asp:Label ID="TweetLabel" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TweetTB" runat="server" Text='<%#Eval("TweetText") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image ID="TweetPic" runat="server"
ImageUrl='<%#"~/UploadedImages/"+Eval("PicName") %>' Height="125px" Width="222px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ReTweet">
<ItemTemplate>
<asp:ImageButton ID="ReTweetImgBTN" runat="server"
ImageUrl="~/SrcImage/retweet-action.png" Height="27px" Width="29px"
CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>'/>
<%--<asp:Label ID="ReTweetEd" runat="server" Text="ReTweetEd" Visible="false"></asp:Label>--%>
<%--<asp:Button ID="ReTweetBTN" runat="server" Text="ReTweet" CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>' />--%>
<asp:Label ID="ReTweetStat" runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Like">
<ItemTemplate>
<asp:ImageButton ID="LikeImgBTN" runat="server" ImageUrl="~/SrcImage/like-action.png"
Height="27px" Width="29px" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>'/>
<%--<asp:Button ID="LikeBTN" runat="server" Text="Like" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>' />--%>
<asp:Label ID="LikeStat" runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options">
<ItemTemplate>
<asp:LinkButton ID="Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="Delete" runat="server" Text="Delete" CommandName="Delete" />
<asp:LinkButton ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:LinkButton ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TweetID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="TweetID" runat="server" Value='<%#Eval("TweetID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="UserID" runat="server" Value='<%#Eval("UserID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
protected void Page_Load(object sender, EventArgs e)
{
Session["UserID"] = 1; // To be removed
if(!IsPostBack)
BindGridview();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int userId = int.Parse(Session["UserID"].ToString());
if (e.CommandName == "Like")
{
int index = Convert.ToInt32(e.CommandArgument);
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
int tweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
LikeHelper.Like(tweetID, userId);
}
else
LikeHelper.Like(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
}
if (e.CommandName == "ReTweet")
{
int index = Convert.ToInt32(e.CommandArgument);
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
int tweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
ReTweetHelper.ReTweet(tweetID, userId);
}
else
ReTweetHelper.ReTweet(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
}
if (e.CommandName == "UnReTweet")
{
int index = Convert.ToInt32(e.CommandArgument);
int RetweetID = ReTweetHelper.GetReTweetIdFromReTweetByUserIdAndTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
int TweetID = NewTweetHelper.GetTweetIdFromTweetByReTweetId(RetweetID);
ReTweetHelper.RemoveReTweet(RetweetID);
NewTweetHelper.GeneralRemoveTweet(TweetID);
}
if (e.CommandName == "Redirect")
{
int index = Convert.ToInt32(e.CommandArgument);
int TweetID = int.Parse(GridView1.DataKeys[index].Value.ToString());
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(TweetID))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(TweetID);
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
int UserID = NewTweetHelper.GetUserIdFromTweetByTweetId(RealTweetID);
Response.Redirect("ProfilePage.aspx?UserName=" + UserHelper.GetUserName(UserID));
}
else
Response.Redirect("ProfilePage.aspx?UserName=" + UserHelper.GetUserName(NewTweetHelper.GetUserIdFromTweetByTweetId(TweetID)));
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
//TextBox TextBox = GridView1.Rows[e.NewEditIndex].FindControl("TweetTB") as TextBox;
//HiddenField TweetID = GridView1.Rows[e.NewEditIndex].FindControl("TweetID") as HiddenField;
//TextBox.Text = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(TweetID.Value.ToString())).TweetText;
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.DataBind();
}
public void BindGridview()
{
int userId = int.Parse(Session["UserID"].ToString());
ServiceReference1.WebServiceSoapClient objWs = new ServiceReference1.WebServiceSoapClient();
DataSet ds = objWs.SelectTweets(userId, 0);
DataTable dt = ds.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userId = int.Parse(Session["UserID"].ToString());
int index = Convert.ToInt32(e.RowIndex);
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
{
int RetweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
ReTweetHelper.RemoveReTweet(RetweetID);
NewTweetHelper.GeneralRemoveTweet(int.Parse(GridView1.DataKeys[index].Value.ToString()));
}
else
NewTweetHelper.GeneralRemoveTweet(Convert.ToInt32(GridView1.DataKeys[index].Value.ToString()));
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int userId = int.Parse(Session["UserID"].ToString());
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField userIdLbl = (HiddenField)e.Row.FindControl("UserID");
HiddenField tweetid = (HiddenField)e.Row.FindControl("TweetID");
LinkButton editBt = (LinkButton)e.Row.FindControl("Edit");
editBt.Visible = userId == Convert.ToInt32(userIdLbl.Value);
ImageButton ProfileImage = e.Row.FindControl("ProfileImage") as ImageButton;
ProfileImage.ImageUrl = "~/UploadedImages/" + UserHelper.GetImageUrl(int.Parse(userIdLbl.Value.ToString()));
// if retweet
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
{
Tweet tweet = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
string FullName = UserHelper.GetName(tweet.UserID);
// change tweet
Label name = e.Row.FindControl("FullNameLabel") as Label;
Label UserName = e.Row.FindControl("UserNameLabel") as Label;
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
int RealUserID = NewTweetHelper.GetUserIdFromTweetByTweetId(RealTweetID);
name.Text = "Retweeted by " + FullName + "<br>" + UserHelper.GetName(RealUserID);
UserName.Text = UserHelper.GetUserName(RealUserID);
ProfileImage.ImageUrl = "~/UploadedImages/" + UserHelper.GetImageUrl(RealUserID);
editBt.Visible = false;
}
//if there is image
Image img = (Image)e.Row.FindControl("TweetPic");
img.Visible = img.ImageUrl != "~/UploadedImages/";
//stats
Label LikeStat = e.Row.FindControl("LikeStat") as Label;
Label ReTweetStat = e.Row.FindControl("ReTweetStat") as Label;
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
LikeStat.Text = LikeHelper.AmountOfLikesByTweetId(RealTweetID).ToString();
if (int.Parse(LikeStat.Text.ToString()) > 0)
LikeStat.Visible = true;
ReTweetStat.Text = ReTweetHelper.AmountOfReTweets(RealTweetID).ToString();
if (int.Parse(ReTweetStat.Text.ToString()) > 0)
ReTweetStat.Visible = true;
}
else
{
LikeStat.Text = LikeHelper.AmountOfLikesByTweetId(int.Parse(tweetid.Value.ToString())).ToString();
if (int.Parse(LikeStat.Text.ToString()) > 0)
LikeStat.Visible = true;
ReTweetStat.Text = ReTweetHelper.AmountOfReTweets(int.Parse(tweetid.Value.ToString())).ToString();
if (int.Parse(ReTweetStat.Text.ToString()) > 0)
ReTweetStat.Visible = true;
}
// retweeted
if (ReTweetHelper.IsReTweetExistByUserIdAndTweetId(userId,int.Parse(tweetid.Value.ToString())))
{
ImageButton Retweet = e.Row.FindControl("ReTweetImgBTN") as ImageButton;
Retweet.ImageUrl = "~/SrcImage/retweet-action-on.png";
Retweet.CommandName = "UnReTweet";
}
if (NewTweetHelper.IsTweetByUser(int.Parse(tweetid.Value.ToString()), userId))
{
ImageButton Retweet = e.Row.FindControl("ReTweetImgBTN") as ImageButton;
Retweet.ImageUrl = "~/SrcImage/retweet-action-inactive.png";
Retweet.CommandName = null;
}
//Like Button
ImageButton LikeImg = e.Row.FindControl("LikeImgBTN") as ImageButton;
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
if(LikeHelper.IsUserLikeTweet(userId,RealTweetID))
LikeImg.ImageUrl = "~/SrcImage/like-action-on.png";
}
else
{
if (LikeHelper.IsUserLikeTweet(userId,int.Parse(tweetid.Value.ToString())))
LikeImg.ImageUrl = "~/SrcImage/like-action-on.png";
}
//Hyper Link Text
Label TweetLabel = (Label)e.Row.FindControl("TweetLabel");
//TextBox TweetTB = (TextBox)e.Row.FindControl("TweetTB");
Tweet TweetText = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
//TweetTB.Text = "a";// TweetText.TweetText.ToString();
string text = NewTweetHelper.HyperLinkTweet(int.Parse(tweetid.Value.ToString()));
//TweetText.TweetText= text; //need?
TweetLabel.Text = text;
//Change Tb in edit cand do it in RowEditting
//if (e.Row.RowState == DataControlRowState.Edit)
//{
// TextBox TextBox = e.Row.FindControl("TweetTB") as TextBox;
// Tweet Text = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
// TextBox.Text = "abc";
//}
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
HiddenField TweetID = GridView1.Rows[e.RowIndex].FindControl("TweetID") as HiddenField;
TextBox TweetText = GridView1.Rows[e.RowIndex].FindControl("TweetTB") as TextBox;
NewTweetHelper.UpdateTweet(int.Parse(TweetID.Value), TweetText.Text);
GridView1.EditIndex = -1;
BindGridview();
}
In the RowEditing event, you can set the EditIndex value and re-bind the data to the GridView:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
Then, in the RowDataBound event, you can access the controls of the row:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == GridView1.EditIndex)
{
TextBox txtBox = e.Row.FindControl("TweetTB") as TextBox;
...
}
else
{
...
}
}
There is a RadGrid inside which there is a RadComboBox (Say ComboIn) and there is 1 more RadComboBox outside of RadGrid (say ComboOut).
When user select any item from ComboOut, then the Items are bind in ComboIn based on selected Item of ComboOut.
I am using LoadOnDemand approach for binding the ComboIn RadComboBox.
Now I want to modify this requirement as: when user click on ComboIn textarea, whole list of items (related to selected ComboOut Item) should not load. Rather when user type/key-in/search the item in ComboIn and click on asp button then only list related to searched text shall load in ComboIn.
Below is the code I am currently using:
HTML
<telerik:RadComboBox ID="ddlCompany" runat="server" Height="200" Width="240"
DropDownWidth="310" EmptyMessage="- Select Product -" HighlightTemplatedItems="true" CausesValidation="false"
Filter="Contains" AppendDataBoundItems="true" AllowCustomText="true" AutoPostBack="true"
DataTextField="Title" DataValueField="Code" OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged">
</telerik:RadComboBox>
<telerik:RadGrid ID="RGGSTAcCode" runat="server"
ShowFooter="True" GroupingEnabled="False" ShowStatusBar="true" EmptyDataText="No record available."
AllowAutomaticInserts="False" AllowAutomaticUpdates="False" AllowAutomaticDeletes="true"
OnNeedDataSource="RGGSTAcCode_NeedDataSource" OnItemDataBound="RGGSTAcCode_ItemDataBound"
OnInsertCommand="RGGSTAcCode_InsertCommand" OnDeleteCommand="RGGSTAcCode_DeleteCommand"
OnUpdateCommand="RGGSTAcCode_UpdateCommand" OnItemCommand="RGGSTAcCode_ItemCommand">
<mastertableview ShowHeadersWhenNoRecords="true" autogeneratecolumns="false" datakeynames="AccountCodeID" InsertItemDisplay="Top"
insertitempageindexaction="ShowItemOnCurrentPage" ShowFooter="True" CommandItemDisplay="Top" ClientIDMode="Static">
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn"></telerik:GridEditCommandColumn>
<telerik:GridBoundColumn DataField="AccountCodeID" HeaderText="AccountCode ID"
UniqueName="AccountCodeID" ReadOnly="True">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310" HighlightTemplatedItems="true" CausesValidation="true"
OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true" ShowDropDownOnTextboxClick="false"
EnableLoadOnDemand="True" ShowMoreResultsBox="true" EnableVirtualScrolling="true" MarkFirstMatch="True"
Filter="Contains" AppendDataBoundItems="true" DataTextField="AccountDescription" DataValueField="AccountCodeID">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridButtonColumn ConfirmTextFormatString="Are you sure you want to Delete {0} Account Code?" ConfirmTextFields="AccountCodeID"
ConfirmDialogType="RadWindow" CommandName="Delete" Text="Delete" UniqueName="DeleteColumn"></telerik:GridButtonColumn>
</Columns>
<EditFormSettings>
<EditColumn ButtonType="ImageButton" />
</EditFormSettings>
<CommandItemSettings AddNewRecordText="Add new record" RefreshText="Refresh"></CommandItemSettings>
</mastertableview>
</telerik:RadGrid>
C#
public DataTable GetAccCode(string CompanyCode)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("[Invoice].[usp_tbl_AccountCode_DL_Test]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyCode", CompanyCode);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
return dt;
}
#region Load on Demand
private const int ItemsPerRequest = 50;
private static string GetStatusMessage(int offset, int total)
{
if (total <= 0)
{
return "No matches";
}
else
{
return String.Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", offset, total);
}
}
protected void ddlAccountCode_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
string c = ddlCompany.SelectedValue.ToString();
DataTable dt = GetAccCode(c);
DataView dv = new DataView(dt);
string txt = e.Text;
dv.RowFilter = string.Format("AccountDescription LIKE '%{0}%'", txt);
int a = dv.Count;
if (dv.Count > 0)
{
dt = dv.ToTable();
}
RadComboBox combo = (RadComboBox)sender;
int itemOffset = e.NumberOfItems;
int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
e.EndOfItems = endOffset == dt.Rows.Count;
for (int i = itemOffset; i < endOffset; i++)
{
combo.Items.Add(new RadComboBoxItem(dt.Rows[i]["AccountDescription"].ToString(), dt.Rows[i]["AccountDescription"].ToString()));
}
if (!string.IsNullOrEmpty(e.Text))
{
int num = dv.Count;
endOffset = dv.Count;
}
e.Message = GetStatusMessage(endOffset, dt.Rows.Count);
}
#endregion
protected void btnSearch_Click(object sender, EventArgs e)
{
}
My code is working fine. Only thing I am not getting is how to bind only search related Items in ComboIn on asp button click. Please reply. Thanks in advance.
Below code solved my query.
Added the _ItemRequested event code inside Button_Click event with few modifications and its working fine now.
C#
protected void ddlAccountCode_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
RadComboBox combo = (RadComboBox)sender;
combo.ShowDropDownOnTextboxClick = false;
combo.Items.Clear();
Session["Text"] = e.Text;
Session["NumberOfItems"] = e.NumberOfItems;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
GridEditableItem editedItem = (sender as Button).NamingContainer as GridEditableItem;
RadComboBox combo = (RadComboBox)editedItem.FindControl("ddlAccountCode");
combo.Items.Clear();
combo.OpenDropDownOnLoad = true;
combo.HighlightTemplatedItems = true;
string c = ddlCompany.SelectedValue.ToString(); //get the selected company name
string txt = Session["Text"].ToString();
DataTable dt = new DataTable();
dt = GetAccCode(c);
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("AccountDescription LIKE '%{0}%'", txt);
int a = dv.Count;
if (dv.Count > 0)
{
dt = dv.ToTable();
}
int itemOffset = Convert.ToInt32(Session["NumberOfItems"]);
int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
Session["NumberOfItems"] = endOffset == dt.Rows.Count;
for (int i = itemOffset; i < dv.Count; i++)
{
combo.Items.Add(new RadComboBoxItem(dt.Rows[i]["AccountDescription"].ToString(), dt.Rows[i]["AccountDescription"].ToString()));
}
Label lbl = (Label)combo.Footer.FindControl("lblRadComboFooter");
lbl.Text = GetStatusMessage(endOffset, dt.Rows.Count);
combo.DataBind();
}
HTML
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240" DropDownWidth="310"
EnableLoadOnDemand="True" OnItemsRequested="ddlAccountCode_ItemsRequested" EnableItemCaching="true"
ShowMoreResultsBox="True" EnableVirtualScrolling="true" AllowCustomText="true" MarkFirstMatch="true"
Filter="Contains" HighlightTemplatedItems="true" CausesValidation="true" AppendDataBoundItems="true"
DataTextField="AccountDescription" DataValueField="AccountCodeID"
ShowDropDownOnTextboxClick="false"
OnClientDropDownOpening="OnClientDropDownOpening" OnClientItemsRequested="OnClientItemsRequested">
<FooterTemplate>
<table style="text-align:center">
<tr>
<td>
<asp:Label ID="lblRadComboFooter" runat="server"></asp:Label>
</td>
</tr>
</table>
</FooterTemplate>
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"/>
</EditItemTemplate>
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