Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

Monday, September 17, 2018

Cascading drop-down list in asp.net Grid view | Dependent Dropdownlist inside GridView


Here i am going to explain how to do cascading drop down list in asp.net webform.code is copied from my project so not able to formatted properly due to lack of time.but you see the code and understand the implementation.

.aspx code
OnRowCommand="gvCity_RowCommand" OnRowEditing="gvCity_RowEditing" OnRowCancelingEdit="gvCity_RowCancelingEdit"
 OnRowUpdating="gvCity_RowUpdating" OnRowDeleting="gvCity_RowDeleting" ShowFooter="True"
 PageSize="20" Width="100%">
 runat="server">
 AutoPostBack="true" OnSelectedIndexChanged="ddlNewCountrygvCity_SelectedIndexChanged"
 Visible="false" runat="server">
 runat="server">
 Visible="false" Enabled="false" runat="server">
 Visible="false">
 OnClientClick="return CityUpdateValidate();" ImageUrl="~/Image/update.png" ToolTip="Update"
 ToolTip="Cancel" ImageUrl="~/Image/cancel.png" />
 CommandName="AddNew" ToolTip="Add New" />
 OnClick="ibtnNewCityInsert_Click" ImageUrl="~/Image/add.png" Visible="false"
 ToolTip="Insert" /> 
 ToolTip="Cancel" ImageUrl="~/Image/cancel.png" Visible="false" />
 ImageUrl="~/Image/img_edit.png" ToolTip="Edit" />
 ImageUrl="~/Image/img_delete.png" OnClientClick="return ConfirmDelete();" ToolTip="Delete"

 .cs code
 public void gvCityBind()
 {
 dsCity = SqlHelper.ExecuteDataset(connectionString, "genCityMaster_SelectDelete", 0, "NULL", "S");
 if (dsCity.Tables[0].Rows.Count > 0)
 {
 gvCity.DataSource = dsCity;
 gvCity.DataBind();
 }
 else
 {
 NoDataFound(dsCity, gvCity);
 SrNoCity = 1;
 }
 }
 protected void gvCity_PageIndexChanging(object sender, GridViewPageEventArgs e)
 {
 gvCity.PageIndex = e.NewPageIndex;
 gvCityBind();
 }
 protected void gvCity_RowDataBound(object sender, GridViewRowEventArgs e)
 {
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
 Label lblSrNo = (Label)e.Row.FindControl("lblSrNo");
 lblSrNo.Text = Convert.ToString(gvCity.PageIndex * gvCity.PageSize + SrNoCity);
 SrNoCity++;
 DropDownList ddlCountry = (DropDownList)e.Row.FindControl("ddlCountry");
 DropDownList ddlState = (DropDownList)e.Row.FindControl("ddlState");
 if (ddlCountry != null)
 {
 ddlCountry.DataSource = objCountryBLL.SelectCounrty();
 ddlCountry.DataBind();
 ddlCountry.SelectedValue = dsCity.Tables[0].Rows[e.Row.RowIndex]["CountryId"].ToString();
 }
 if (ddlState != null)
 {
 ddlState.DataSource = objStateBLL.SelectState(Convert.ToInt32(ddlCountry.SelectedValue));
 ddlState.DataBind();
 ddlState.SelectedValue = dsCity.Tables[0].Rows[e.Row.RowIndex]["StateId"].ToString();
 }
 }
 if (e.Row.RowType == DataControlRowType.Footer)
 {
 DropDownList ddlNewCountry = (DropDownList)e.Row.FindControl("ddlNewCountry");
 DropDownList ddlNewState = (DropDownList)e.Row.FindControl("ddlNewState");
 if (ddlNewCountry != null)
 {
 ddlNewCountry.DataSource = objCountryBLL.SelectCounrty();
 ddlNewCountry.DataBind();
 }
 if (ddlNewState != null)
 {
 ddlNewState.DataSource = objStateBLL.SelectState(Convert.ToInt32(ddlNewCountry.SelectedValue));
 ddlNewState.DataBind();
 }
 }
 }
 protected void gvCity_RowCommand(object sender, GridViewCommandEventArgs e)
 {
 try
 {
 if (e.CommandName.Equals("AddNew"))
 {
 gvCity.EditIndex = -1;
 gvCityBind();
 gvCity.FooterRow.CssClass = objCommonDAL.GetGrigViewFooterStyle();
 Label lblNewSrNo = (Label)gvCity.FooterRow.FindControl("lblNewSrNo");
 lblNewSrNo.Text = SrNoCity.ToString();
 ImageButton ibtnNewCityInsert = (ImageButton)gvCity.FooterRow.FindControl("ibtnNewCityInsert");
 ImageButton imgbtnNewCancel = (ImageButton)gvCity.FooterRow.FindControl("imgbtnNewCancel");
 ImageButton imgbtnNewAdd = (ImageButton)gvCity.FooterRow.FindControl("imgbtnNewAdd");
 ibtnNewCityInsert.Visible = true;
 imgbtnNewCancel.Visible = true;
 imgbtnNewAdd.Visible = false;
 DropDownList ddlNewCountry = (DropDownList)gvCity.FooterRow.FindControl("ddlNewCountry");
 ddlNewCountry.Visible = true;
 ddlNewCountry.Focus();
 DropDownList ddlNewState = (DropDownList)gvCity.FooterRow.FindControl("ddlNewState");
 ddlNewState.Visible = true;
 TextBox txtNewCity = (TextBox)gvCity.FooterRow.FindControl("txtNewCity");
 txtNewCity.Visible = true;
 }
 }
 catch (Exception ex)
 {
 throw ex;
 }
 }
 protected void ibtnNewCityInsert_Click(object sender, ImageClickEventArgs e)
 {
 try
 {
 objCity.StateId = Convert.ToInt32(((DropDownList)gvCity.FooterRow.FindControl("ddlNewState")).SelectedValue);
 objCity.CityName = Convert.ToString(((TextBox)gvCity.FooterRow.FindControl("txtNewCity")).Text);
 objCity.CreatedBy = Convert.ToInt32(UserId);
 objCity.ModifiedBy = Convert.ToInt32(UserId);
 objCity.CreatedOn = System.DateTime.Now;
 objCity.ModifiedOn = System.DateTime.Now;
 try
 {
 int intResultInsert = objCityBLL.InsertCity(objCity);
 if (intResultInsert > 0)
 {
 exceptionMessage.Text = "Record Added Successfully !";
 gvCity.EditIndex = -1;
 gvCityBind();
 }
 else
 {
 exceptionMessage.Text = "This record already exists !";
 }
 }
 catch (Exception ex)
 {
 exceptionMessage.Text = ex.Message.ToString();
 }
 finally
 {
 objCityBLL = null;
 }
 }
 catch (Exception ex)
 {
 throw ex;
 }
 }
 protected void gvCity_RowEditing(object sender, GridViewEditEventArgs e)
 {
 gvCity.EditIndex = e.NewEditIndex;
 gvCityBind();
 }
 protected void gvCity_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
 {
 gvCity.EditIndex = -1;
 gvCityBind();
 }
 protected void gvCity_RowUpdating(object sender, GridViewUpdateEventArgs e)
 {
 try
 {
 objCity.CityId = Convert.ToInt32(((Label)gvCity.Rows[e.RowIndex].FindControl("lblCityId")).Text);
 objCity.StateId = Convert.ToInt32(((DropDownList)gvCity.Rows[e.RowIndex].FindControl("ddlState")).SelectedValue);
 objCity.CityName = Convert.ToString(((TextBox)gvCity.Rows[e.RowIndex].FindControl("txtCity")).Text);
 objCity.CreatedBy = Convert.ToInt32(UserId);
 objCity.ModifiedBy = Convert.ToInt32(UserId);
 objCity.CreatedOn = System.DateTime.Now;
 objCity.ModifiedOn = System.DateTime.Now;
 int intResultUpdate = objCityBLL.UpdateCity(objCity);
 if (intResultUpdate > 0)
 {
 exceptionMessage.Text = "Record Updated Successfully !";
 gvCity.EditIndex = -1;
 gvCityBind();
 }
 }
 catch (Exception ex)
 {
 exceptionMessage.Text = ex.Message.ToString();
 }
 finally
 {
 objCityBLL = null;
 }
 }
 protected void gvCity_RowDeleting(object sender, GridViewDeleteEventArgs e)
 {
 try
 {
 objCity.CityId = (int)gvCity.DataKeys[e.RowIndex].Value;
 int result = objCityBLL.DeleteCity(objCity);
 if (result > 0)
 {
 exceptionMessage.Text = "Row Deleted Successfully...!";
 gvCity.EditIndex = -1;
 gvCityBind();
 }
 }
 catch (Exception ex)
 {
 exceptionMessage.Text = ex.Message.ToString();
 }
 }
 protected void ddlNewCountrygvCity_SelectedIndexChanged(object sender, EventArgs e)
 {
 DropDownList ddlNewCountry = (DropDownList)gvCity.FooterRow.FindControl("ddlNewCountry");
 DropDownList ddlNewState = (DropDownList)gvCity.FooterRow.FindControl("ddlNewState");
 if (Convert.ToInt32(ddlNewCountry.SelectedValue) > 0)
 {
 ddlNewState.Enabled = true;
 ddlNewState.DataSource = objStateBLL.SelectState(Convert.ToInt32(ddlNewCountry.SelectedValue));
 ddlNewState.DataBind();
 }
 else
 {
 ddlNewState.Enabled = false;
 }
 } 

Saturday, September 18, 2010

GridView with checkbox

This article is very simple.Many time developer need to how develop Gridview with checkbox,so we can select single or multiple record to update.
Javascript file
 <script language="javascript" type="text/javascript">  
function SelectAllCheckboxes(spanChk)
{
var oItem = spanChk.children;
var theBox=(spanChk.type=="checkbox")?spanChk:spanChk.children.item[0];
xState=theBox.checked;
elm=theBox.form.elements;
for(i=0;i if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)
{
if(elm[i].checked!=xState)
elm[i].click();
}
}
</script>


Html code

 <form id="form1" runat="server">  
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CustomerID" Width="366px" CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" InsertVisible="False" ReadOnly="True" SortExpression="PersonID" />
<asp:BoundField DataField="Fname" HeaderText="Fname" SortExpression="Fname" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" type="checkbox" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Delete" />
<asp:Label ID="lblmsg" runat="server" Text="Label" Visible="false"></asp:Label>
</form>


.cs code
 public partial class GridWithCheck : System.Web.UI.Page  
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConnect"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
public void BindGridView()
{
SqlDataAdapter ad = new SqlDataAdapter("select * from tbl_CustomerDetail order by CustomerID", con);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = ((CheckBox)(row.FindControl("chkSelect")));
if (cb != null && cb.Checked)
{
int custID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
string sqlstr = "delete from tbl_CustomerDetail where CustomerID='" + custID + "'";
SqlCommand mycmd;
mycmd = new SqlCommand(sqlstr, con);
con.Open();
mycmd.ExecuteNonQuery();
Page.RegisterStartupScript("pop", "&lt;script&gt;alert('Row deleted')&lt;/script&gt;");
BindGridView();
}
}
}
}

Thanks & Regards
Santosh

Friday, September 17, 2010

How to bind GridView with DataSet in ASP.Net and c#

  How to bind GridView with DataSet in ASP.Net and c#.  
  In this article I am using ASP.Net GridView control to display data from database.I am using Dataset to fill data and display in Grid.  
  protected void Page_Load(object sender, EventArgs e)   
  {   
       if (!Page.IsPostBack)   
       {   
           bindGridView();   
       }   
  }   
  public void bindGridView()   
  {   
       SqlConnection myconnection;   
       SqlCommand mycmd;   
       SqlDataAdapter myda;   
       DataSet ds;   
       myconnection = new SqlConnection("Data Source=YourServer;Initial Catalog=Test;Integrated Security=True");   
       myda = new SqlDataAdapter("Select * from tblCustDetail ", myconnection);   
       ds = new DataSet();   
       myda.Fill(ds);   
       gvCust.DataSource = ds;   
       gvCust.DataBind();   
  }  

Thursday, September 16, 2010

How to bind data to DropDownList in GridView in ASP.Net and C#

 How to bind data to DropDownList in GridView in ASP.Net and C#  
 In this article i am explaining how to bind data to DropDownList inside asp.net GridView control.  
 protected void GridDegree_RowDataBound(object sender, GridViewRowEventArgs e)  
 {  
      if (e.Row.RowType == DataControlRowType.DataRow)  
      {   
           DropDownList ddlDegreeType = (DropDownList)e.Row.FindControl("ddlDegreeType");  
           if (ddlDegreeType != null)  
           {  
                ddlDegreeType.DataSource = objDegreeDAL.GetDegree();   
                ddlDegreeType.DataBind();  
                ddlDegreeType.SelectedValue = dsDegree.Tables[0].Rows[e.Row.RowIndex]["DegreeId"].ToString();  
           }  
      }  
 }  
 .aspx page   
 <asp:TemplateField HeaderText="Degree Type>  
      <ItemTemplategt>  
           <asp:Label ID="lblDegreeType" runat="server" Text='<%# Bind("[Degree]") %></asp:Label>  
      </ItemTemplategt>  
      <EditItemTemplate>  
      <asp:DropDownList ID="ddlDegreeType" runat="server" DataTextField="Degree"  
      DataValueField="Degreeid>  
      </asp:DropDownList>  
      </EditItemTemplate>  
 </asp:TemplateField>  

Wednesday, September 15, 2010

Create pdf from GridView control in asp.net with c#

 Create pdf from GridView using asp.net with c#  
 Here this article show full code for create the pdf file from asp.net GridView.  
 Some time developer need how to do GridView to pdf .Here i have written the method according to my requirement.You can change according to your requirement and use this.  
 public void ConvertDataInPdf(DataTable dtExportInPdf, string reportName, string OtherInfo)  
 {  
      try  
      {  
           float CompanyNameSize = 11;  
           float ReportNameSize = 9;  
           float HeaderTextSize = 7;  
           float ReportTextSize = 6;  
           int totalWidth = 0;  
           int tableWidthPercent = 100;  
           int[] widths = new int[dtExportInPdf.Columns.Count];  
           for (int h = 0; h < dtExportInPdf.Columns.Count; h++) //Data table header column width  
           {  
                string strWidth = dtExportInPdf.Columns[h].ToString();  
                widths[h] = strWidth.Length;  
           }  
           foreach (DataRow dr in dtExportInPdf.Rows) //Data table column width  
           {  
                int[] colItemWidth = new int[dtExportInPdf.Columns.Count];  
                for (int i = 0; i < dtExportInPdf.Columns.Count; i++) //Data table max item width  
                {  
                     if (dr[i].ToString().Length > 20)  
                     {  
                          colItemWidth[i] = 20;  
                     }  
                     else if (dr[i].ToString().Length < 3)  
                     {  
                          colItemWidth[i] = 3;  
                     }  
                     else  
                     {  
                          colItemWidth[i] = dr[i].ToString().Length;  
                     }  
                     if (colItemWidth[i] > widths[i])  
                     {  
                          widths[i] = colItemWidth[i];  
                     }  
                }  
           }  
           for (int h = 0; h < dtExportInPdf.Columns.Count; h++)  
           {  
                totalWidth += widths[h];  
           }  
           Document pdfDoc = null;  
           if (totalWidth > 0 && totalWidth <= 110)  
           {  
                pdfDoc = new Document(PageSize.A4, 20, 20, 20, 20);  
           }  
           else if (totalWidth > 110 && totalWidth <= 160)  
           {  
                pdfDoc = new Document(PageSize.A4.Rotate(), 20, 20, 20, 20);  
           }  
           else if (totalWidth > 160 && totalWidth <= 250)  
           {  
                HeaderTextSize = 6;  
                ReportTextSize = 5;  
                pdfDoc = new Document(PageSize.LEGAL.Rotate(), 20, 20, 20, 20);  
           }  
           else if (totalWidth > 250 && totalWidth <= 300)  
           {  
                CompanyNameSize = 9;  
                ReportNameSize = 7;  
                HeaderTextSize = 6;  
                ReportTextSize = 5;  
                pdfDoc = new Document(PageSize.B1, 20, 20, 20, 20);  
           }  
           else if (totalWidth > 300)  
           {  
                CompanyNameSize = 9;  
                ReportNameSize = 7;  
                HeaderTextSize = 6;  
                ReportTextSize = 5;  
                pdfDoc = new Document(PageSize.B1.Rotate(), 20, 20, 20, 20);  
           }  
           // Creates a PdfPTable with column count of the table equal to no of columns of the datatable or gridview or gridview datasource.  
           PdfPTable pdfTable = new PdfPTable(dtExportInPdf.Columns.Count);  
           pdfTable.WidthPercentage = tableWidthPercent;  
           pdfTable.HeaderRows = 4; // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.  
           #region PDFHeader  
           PdfPTable headerTable = new PdfPTable(3); // Creates a PdfPTable with 3 columns to hold the header in the exported PDF.  
           byte[] logo = (byte[])System.Web.HttpContext.Current.Session["Logo"];  
           iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(logo);  
           imgLogo.ScaleToFit(80f, 40f);//Resize image depend upon your need   
           imgLogo.SpacingBefore = 0f;//Give space before image   
           imgLogo.SpacingAfter = 1f;//Give some space after the image   
           PdfPCell clLogo = new PdfPCell(imgLogo);// Creates a PdfPCell which accepts a phrase as a parameter.  
           clLogo.Border = PdfPCell.NO_BORDER;// Sets the border of the cell to zero.  
           clLogo.HorizontalAlignment = Element.ALIGN_LEFT;// Sets the Horizontal Alignment of the PdfPCell to left.  
           clLogo.VerticalAlignment = Element.ALIGN_MIDDLE;  
           // Creates a phrase to hold the application name at the left hand side of the header.  
           Phrase phApplicationName = new Phrase("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Arial", CompanyNameSize, iTextSharp.text.Font.NORMAL));  
           PdfPCell clApplicationName = new PdfPCell(phApplicationName);// Creates a PdfPCell which accepts a phrase as a parameter.  
           clApplicationName.Border = PdfPCell.NO_BORDER;// Sets the border of the cell to zero.  
           clApplicationName.HorizontalAlignment = Element.ALIGN_CENTER;// Sets the Horizontal Alignment of the PdfPCell to left.  
           clApplicationName.VerticalAlignment = Element.ALIGN_MIDDLE;  
           // Creates a phrase to show the current date at the right hand side of the header.  
           Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", 7, iTextSharp.text.Font.NORMAL));  
           PdfPCell clDate = new PdfPCell(phDate);// Creates a PdfPCell which accepts the date phrase as a parameter.  
           clDate.HorizontalAlignment = Element.ALIGN_RIGHT;// Sets the Horizontal Alignment of the PdfPCell to right.  
           clDate.Border = PdfPCell.NO_BORDER;// Sets the border of the cell to zero.  
           clDate.VerticalAlignment = Element.ALIGN_MIDDLE;  
           headerTable.AddCell(clLogo);  
           headerTable.AddCell(clApplicationName);// Adds the cell which holds the application name to the headerTable.  
           headerTable.AddCell(clDate);// Adds the cell which holds the date to the headerTable.  
           headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;// Sets the border of the headerTable to zero.   
           // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.  
           PdfPCell cellHeader = new PdfPCell(headerTable);  
           cellHeader.VerticalAlignment = Element.ALIGN_TOP;  
           cellHeader.Border = PdfPCell.NO_BORDER;  
           cellHeader.Colspan = dtExportInPdf.Columns.Count;// Sets the column span of the header cell to noOfColumns.  
           pdfTable.AddCell(cellHeader);// Adds the above header cell to the table.  
           #endregion PDFHeader  
           //Creates a phrase for a new line.  
           Phrase phSpace1 = new Phrase("\n");  
           PdfPCell clSpace1 = new PdfPCell(phSpace1);  
           clSpace1.Border = PdfPCell.BOTTOM_BORDER;  
           clSpace1.BorderWidth = 1;  
           clSpace1.BorderColor = iTextSharp.text.Color.DARK_GRAY;  
           clSpace1.Colspan = dtExportInPdf.Columns.Count;  
           pdfTable.AddCell(clSpace1);  
           // Creates a phrase to hold the report name.  
           Phrase phHeader = new Phrase("" + reportName + "", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.NORMAL));  
           PdfPCell clHeader = new PdfPCell(phHeader);  
           clHeader.Colspan = dtExportInPdf.Columns.Count;  
           clHeader.Border = PdfPCell.NO_BORDER;  
           clHeader.HorizontalAlignment = Element.ALIGN_CENTER;  
           clHeader.VerticalAlignment = Element.ALIGN_MIDDLE;  
           clHeader.PaddingTop = 5;  
           clHeader.PaddingBottom = 2;  
           pdfTable.AddCell(clHeader);  
           //Create Phrage to hold other informations  
           Phrase phOtherInfo = new Phrase(OtherInfo, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));  
           PdfPCell cellOtherInfo = new PdfPCell(phOtherInfo);  
           cellOtherInfo.Colspan = dtExportInPdf.Columns.Count;  
           cellOtherInfo.Border = Element.ALIGN_LEFT;  
           cellOtherInfo.PaddingBottom = 10;  
           pdfTable.AddCell(cellOtherInfo);  
           PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);  
           string strFooter = "Copyright © 2010 By Cnergee. Page:";  
           Phrase phCopyright = new Phrase(strFooter, FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.NORMAL));  
           Phrase phPageNo = new Phrase("", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.NORMAL));  
           HeaderFooter footer = new HeaderFooter(phCopyright, phPageNo);  
           //footer.Alignment = Element.ALIGN_LEFT;  
           footer.Alignment = Element.ALIGN_RIGHT;  
           footer.Border = iTextSharp.text.Rectangle.TOP_BORDER;  
           footer.GrayFill = 10;  
           pdfDoc.Footer = footer;  
           pdfDoc.Open();  
           Font font8 = FontFactory.GetFont("ARIAL Narrow", 7);  
           if (dtExportInPdf != null)  
           {  
                pdfDoc.Header = null;  
                //Create header for pdf table  
                string cloName = null;  
                Phrase ph = null;  
                for (int i = 0; i < dtExportInPdf.Columns.Count; i++)  
                {  
                     cloName = dtExportInPdf.Columns[i].ColumnName;  
                     if (dtExportInPdf.Columns.Count > 0)  
                     {  
                          ph = new Phrase(cloName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));  
                     }  
                     else  
                     {  
                          ph = new Phrase(cloName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));  
                     }  
                     pdfTable.AddCell(ph);  
                }  
                //Add data into the pdf table   
                for (int rows = 0; rows < dtExportInPdf.Rows.Count; rows++)  
                {  
                ph = null;  
                PdfPCell pCell = null;  
                for (int column = 0; column < dtExportInPdf.Columns.Count; column++)  
                {  
                     ph = new Phrase(dtExportInPdf.Rows[rows][column].ToString(), FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));  
                     pCell = new PdfPCell(ph);  
                     if (dtExportInPdf.Columns[column].ColumnName == "SrNo" || dtExportInPdf.Columns[column].ColumnName == "Sr.No." || dtExportInPdf.Columns[column].ColumnName == "Sr. No." || dtExportInPdf.Columns[column].ColumnName == "Code" || dtExportInPdf.Columns[column].ColumnName == "EmpCode" || dtExportInPdf.Columns[column].ColumnName == "EmployeeCode")  
                     {  
                          pCell.HorizontalAlignment = Element.ALIGN_CENTER;  
                     }  
                     else if (dtExportInPdf.Columns[column].ColumnName == "Amount")  
                     {  
                          pCell.HorizontalAlignment = Element.ALIGN_RIGHT;  
                     }  
                     else if (dtExportInPdf.Columns[column].ColumnName == "Date" || dtExportInPdf.Columns[column].ColumnName == "From" || dtExportInPdf.Columns[column].ColumnName == "To")  
                     {  
                          pCell.HorizontalAlignment = Element.ALIGN_CENTER;  
                     }  
                     else  
                     {  
                          pCell.HorizontalAlignment = Element.ALIGN_LEFT;  
                     }  
                     pdfTable.AddCell(pCell);  
                }  
                pdfTable.SetWidths(widths);  
                }  
                pdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table   
                pdfDoc.Add(pdfTable); // add pdf table to the document   
           }  
           pdfDoc.Close();  
           string pdfFileName = reportName;  
           reportName = reportName.Replace(" ", "");  
           System.Web.HttpContext.Current.Response.ContentType = "application/pdf";  
           System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename= " + pdfFileName + ".pdf");  
           System.Web.HttpContext.Current.Response.Write(pdfDoc);  
           System.Web.HttpContext.Current.Response.Flush();  
           System.Web.HttpContext.Current.Response.End();  
      }  
      catch (DocumentException de)  
      {  
           System.Web.HttpContext.Current.Response.Write(de.Message);  
      }  
      catch (IOException ioEx)  
      {  
           System.Web.HttpContext.Current.Response.Write(ioEx.Message);  
      }  
      catch (Exception ex)  
      {  
           System.Web.HttpContext.Current.Response.Write(ex.Message);  
      }  
 }  

Friday, September 10, 2010

Javascript validation for Gridview footer textbox

 Javascript validation for Gridview footer textbox  
 Here gridview have footer row that cantain dropdownlist and two textbox.This javascript validate these fields while inserting record in database.  
 function ValidateGrid()  
 {   
      ddlNewCountry = document.getElementById('<%=((DropDownList)gv.FooterRow.FindControl("ddlNewCountry")).ClientID%>');  
      txtNewEmpName = document.getElementById('<%=((TextBox)gv.FooterRow.FindControl("txtNewEmpName")).ClientID %>');  
      txtNewAge = document.getElementById('<%=((TextBox)gv.FooterRow.FindControl("txtNewAge")).ClientID %>');  
      if(ddlNewCountry.value == 0)  
      {  
           alert("Please Select Country...!");  
           ddlNewCountry.focus();  
           return false;  
      }  
      if(txtNewEmpName.value == 0)  
      {  
           alert("Please Enter Emp name...!");  
           txtNewEmpName.focus();  
           return false;  
      }  
      if(txtNewAge.value == 0)  
      {  
           alert("Please Enter age...!");  
           txtNewAge.focus();  
           return false;  
      }   
      return true;   
 }  

Javascript validation for Gridview in edit mode

 Javascript validation for Gridview textbox in edit mode  
 Clientside validation for Gridview textboxex while edting record.  
 Here gridview have dropdownlist and two textbox.This javascript clientside code validate these fields while edting record.   
 function ValidateGridEditMode()  
 {  
      var Gid = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer').rows.length;  
      var i;  
      for(i=2; i <=Gid; i++)  
      {   
           if(i<10)  
           {  
                ddlCustLocation = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl0'+i+'_ddlCustLocation');  
                txtCustCode = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl0'+i+'_txtCustCode');  
                txtCustName = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl0'+i+'_txtCustName');   
           }  
           else  
           {  
                ddlCustLocation = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl'+i+'_ddlCustLocation');  
                txtCustCode = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl'+i+'_txtCustCode');  
                txtCustName = document.getElementById('ctl00_ContentPlaceHolder1_TabContaner_tabCustomer_gvCustomer_ctl'+i+'_txtCustName');   
           }  
           ddlCustLocation != null || txtCustCode != null || txtCustName != null)  
           {  
                ddlCustLocation == 0)  
                {  
                     alert("Please Select Location..");  
                     ddlCustLocation.focus();  
                     return false;  
                }   
                else  
                {  
                     if(txtCustCode.value == 0)  
                     {  
                          alert("Please enter Customer Code..");   
                          txtCustCode.focus();   
                          return false;  
                     }   
                     else  
                     {  
                          if(txtCustName.value == "")  
                          {  
                               alert("Please enter Customer Name ..");   
                               txtCustName.focus();   
                               return false;  
                          }  
                     }   
                }   
           }   
      }  
      return true;  
 }  

Gridview control with Edit Delete and Update in ASP.NET using C#

 Gridview control with Edit Delete and Update in ASP.NET  
 Gridview Edit/Delete/Update using sqlhelper class and 3 layer architecture.  
 In this article I have tried to make the simple Add , Edit, Update and Delete functions in ASP.Net GridView.  
 Feature of this GridView  
 1.This example used three tier architecture.  
 2.Add new record using footer.  
 3.Update and delete record.  
 4.For edit and delete i have used image button for nice look.  
 5.If table is empty(No record in table) a blank dynamic Gridview display for with Add New buttion.  
 6.On Click Edit or Add New cursor focus to Textbox.  
 7.Auto Generated Serial Number In Gridview Control.  
 I have used property layer but i didnt write here,i think you can implement it according to your logic.  
 MySample.aspx page  
 <asp:GridView ID="GridViewEmpSkill" runat="server" AllowPaging="True" AutoGenerateColumns="False"  
 PageSize="12" OnPageIndexChanging="GridViewEmpSkill_PageIndexChanging" OnRowDataBound="GridViewEmpSkill_RowDataBound"  
 TabIndex="2" Width="697px" OnRowCancelingEdit="GridViewEmpSkill_RowCancelingEdit" OnRowEditing="GridViewEmpSkill_RowEditing"  
 OnRowUpdating="GridViewEmpSkill_RowUpdating" ShowFooter="True" OnRowCommand="GridViewEmpSkill_RowCommand"  
 OnRowDeleting="GridViewEmpSkill_RowDeleting" DataKeyNames="EmpSkillId">  
      <Columns>  
           <asp:TemplateField HeaderText="Sr No">  
                <ItemTemplate>  
                <asp:Label ID="lblSrNo" runat="server"></asp:Label>  
                </ItemTemplate>  
                <FooterTemplate>  
                <asp:Label ID="lblNewSrNo" runat="server"></asp:Label>  
                </FooterTemplate>  
                <ItemStyle HorizontalAlign="Center" Width="50px" />  
           </asp:TemplateField>  
           <asp:TemplateField HeaderText="EmpSkillId" Visible="False">  
                <ItemTemplate>  
                <asp:Label ID="lblEmpSkillId" runat="server" Text='<%# Bind("EmpSkillId") %>'></asp:Label>  
                </ItemTemplate>  
           </asp:TemplateField>  
           <asp:TemplateField HeaderText="EmpSkill">  
                <EditItemTemplate>  
                <asp:TextBox ID="txtEmpSkill" runat="server" Width="493px" BorderColor="White" BorderWidth="0px"  
                Height="14px" Text='<%# Bind("EmpSkill") %>'></asp:TextBox>  
                </EditItemTemplate>  
                <FooterTemplate>  
                <asp:TextBox ID="txtNewEmpSkill" runat="server" Width="493px" BorderColor="White" BorderWidth="0px"  
                Height="14px" Visible="false"></asp:TextBox>  
                </FooterTemplate>  
                <ItemTemplate>  
                <asp:Label ID="lblEmpSkill" runat="server" Text='<%# Bind("EmpSkill") %>'></asp:Label>  
                </ItemTemplate>  
                <FooterStyle HorizontalAlign="Left" />  
                <ItemStyle HorizontalAlign="Left" />  
           </asp:TemplateField>  
           <asp:TemplateField HeaderText="Activity">  
                <ItemTemplate>  
                <asp:ImageButton ID="imgEdit" runat="server" ImageUrl="~/Image/img_edit.png" CommandName="Edit" ToolTip="Edit" />  
                <asp:ImageButton ID="imgbtnDelete" runat="server" ImageUrl="~/Image/img_delete.png" ToolTip="Delete"  
                CommandName="Delete" OnClientClick="return ConfirmDelete();" />  
                </ItemTemplate>  
                <EditItemTemplate>  
                <asp:ImageButton ID="imgUpdate" runat="server" CausesValidation="True" CommandName="Update" ToolTip="Update"  
                ImageUrl="~/Image/update.png" Text="Update" />  
                <asp:ImageButton ID="imgCancel" runat="server" CausesValidation="False" CommandName="Cancel" ToolTip="Cancel"  
                ImageUrl="~/Image/cancel.png" Text="Cancel" />  
                </EditItemTemplate>  
                <FooterTemplate>  
                <asp:ImageButton ID="imgNewAdd" runat="server" ImageUrl="~/Image/row_add.png"  
                CommandName="AddNew" ToolTip="Add New" />  
                <asp:ImageButton ID="imgbtnNewInsert" runat="server" CausesValidation="True" CommandName="Insert" ToolTip="Save"  
                ImageUrl="~/Image/add.png" Visible="false" Text="Add" />  
                <asp:ImageButton ID="imgNewCancel" runat="server" CausesValidation="False" CommandName="Cancel" ToolTip="Cancel"  
                ImageUrl="~/Image/cancel.png" Visible="false" Text="Cancel" />  
                </FooterTemplate>  
                <FooterStyle HorizontalAlign="Center" Width="140px" />  
                <ItemStyle HorizontalAlign="Center" Width="140px" />  
           </asp:TemplateField>  
      </Columns>  
 </asp:GridView>  
 ===========  
 MySample.cs page  
 protected void GridViewEmployeeSkill()  
 {  
      try  
      {  
           Ds = SkillBLLobj.GetEmpSkillData();  
           if (Ds.Tables[0].Rows.Count > 0)  
           {  
                GridViewEmpSkill.DataSource = Ds;  
                GridViewEmpSkill.DataBind();  
           }  
           else  
           {  
                ShowNoResultFound(Ds,GridViewEmpSkill);  
                SrNoSkill = 1;  
           }  
      }  
      catch (Exception ex)  
      {  
           msgEmpSkill.Text = ex.Message;  
      }  
 }  
 protected void GridViewEmpSkill_RowEditing(object sender, GridViewEditEventArgs e)  
 {  
      GridViewEmpSkill.EditIndex = e.NewEditIndex;  
      GridViewEmpSkill();  
      GridViewEmpSkill.Rows[e.NewEditIndex].FindControl("txtEmpSkill").Focus();  
 }  
 protected void GridViewEmpSkill_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
 {  
      GridViewEmpSkill.EditIndex = -1;  
      GridViewSkill();  
 }  
 protected void GridViewEmpSkill_PageIndexChanging(object sender, GridViewPageEventArgs e)  
 {  
      GridViewEmpSkill.PageIndex = e.NewPageIndex;  
      GridViewSkill();  
 }  
 protected void GridViewEmpSkill_RowDataBound(object sender, GridViewRowEventArgs e)  
 {  
      if (e.Row.RowType == DataControlRowType.DataRow)  
      {  
           Label lblSrNo = (Label)e.Row.FindControl("lblSrNo");  
           lblSrNo.Text = SrNo.ToString();  
           SrNo++;   
      }  
 }  
 protected void GridViewEmpSkill_RowUpdating(object sender, GridViewUpdateEventArgs e)  
 {  
      try  
      {   
           SkillClsobj.SkillId = Convert.ToInt32(((Label)GridViewEmpSkill.Rows[e.RowIndex].FindControl("lblEmpSkillId")).Text);  
           SkillClsobj.Skill = Convert.ToString(((TextBox)GridViewEmpSkill.Rows[e.RowIndex].FindControl("txtEmpSkill")).Text);  
           int Update = SkillBLLobj.UpdateEmpSkill(SkillClsobj);  
           if (Update > 0)  
           {  
                msgEmpSkill.Text = "Record Updated Successfully !";  
                GridViewEmpSkill.EditIndex = -1;  
                GridViewSkill();  
           }  
      }  
      catch (Exception ex)  
      {  
           msgEmpSkill.Text = ex.Message.ToString();  
      }  
 }  
 protected void GridViewEmpSkill_RowCommand(object sender, GridViewCommandEventArgs e)  
 {  
      try  
      {  
      if (e.CommandName.Equals("AddNew") || e.CommandName.Equals("Insert"))  
      {  
      if (e.CommandName.Equals("AddNew"))  
      {  
      GridViewEmpSkill.EditIndex = -1;  
      GridViewSkill();   
      Label lblNewSrNo = (Label)GridViewEmpSkill.FooterRow.FindControl("lblNewSrNo");  
      lblNewSrNo.Text = SrNo.ToString();  
      ImageButton imgNewInsert = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewInsert");  
      ImageButton imgNewCancel = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewCancel");  
      ImageButton imgNewAdd = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewAdd");  
      imgNewInsert.Visible = true;  
      imgNewCancel.Visible = true;  
      imgNewAdd.Visible = false;  
      TextBox txtNewEmpSkill = (TextBox)GridViewEmpSkill.FooterRow.FindControl("txtNewEmpSkill");  
      txtNewEmpSkill.Visible = true;  
      txtNewEmpSkill.Focus();  
      }  
      }  
      }  
      catch(Exception ex)  
      {  
      throw ex;  
      }  
      try  
      {  
           if (e.CommandName.Equals("Insert"))  
           {  
                ImageButton imgNewInsert = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewInsert");  
                ImageButton imgNewCancel = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewCancel");  
                ImageButton imgNewAdd = (ImageButton)GridViewEmpSkill.FooterRow.FindControl("imgNewAdd");  
                imgNewInsert.Visible = false;  
                imgNewCancel.Visible = false;  
                imgNewAdd.Visible = true;  
                TextBox txtNewSkill = (TextBox)GridViewEmpSkill.FooterRow.FindControl("txtNewEmpSkill");  
                txtNewEmpSkill.Visible = true;  
                txtNewEmpSkill.Focus();  
                SkillClsobj.Skill = Convert.ToString(((TextBox)GridViewEmpSkill.FooterRow.FindControl("txtNewSkill")).Text);  
                try  
                {  
                     if (SkillClsobj.Skill == "")  
                     {  
                          msgEmpSkill.Text = "Pleae Enter !";  
                     }  
                     else  
                     {  
                          int intResult= SkillBLLobj.InsertEmpSkill(SkillClsobj);  
                          if (intResult> 0)  
                          {  
                               msgEmpSkill.Text = "Record Added !";  
                               GridViewEmpSkill.EditIndex = -1;  
                               GridViewSkill();  
                          }  
                     }  
                }  
                catch (Exception ee)  
                {  
                     msgEmpSkill.Text = ee.Message.ToString();  
                }  
                finally  
                {  
                     SkillBLLobj = null;  
                }  
           }  
      }  
      catch(Exception ex)  
      {  
      throw ex;  
      }  
 }  
 protected void GridViewEmpSkill_RowDeleting(object sender, GridViewDeleteEventArgs e)  
 {  
      try  
      {  
           SkillClsobj.SkillId = (int)GridViewEmpSkill.DataKeys[e.RowIndex].Value;  
           int result = SkillBLLobj.DeleteSkill(SkillClsobj);  
           if (result > 0)  
           {  
                msgEmpSkill.Text = "Record Deleted Successfully !";  
                GridViewEmpSkill.EditIndex = -1;  
                GridViewSkill();  
           }  
      }  
      catch (Exception ex)  
      {  
           msgEmpSkill.Text = ex.Message.ToString();  
      }  
 }  
 private void ShowNoResultFound(DataSet ds,GridView gv)  
 {  
      DataTable dt = (DataTable)ds.Tables[0];  
      dt.Rows.Add(dt.NewRow());  
      gv.DataSource = dt;  
      gv.DataBind();  
      int TotalColumns = gv.Rows[0].Cells.Count;  
      gv.Rows[0].Cells.Clear();  
      gv.Rows[0].Cells.Add(new TableCell());  
      gv.Rows[0].Height = 0;  
      gv.Rows[0].Visible = false;  
 }  
 ======================  
 business logic layer  
 public class EmpSkillBLL  
 {  
      EmpSkillDAL SkillDALobj = new EmpSkillDAL();  
      public DataSet GetEmpSkillData()  
      {  
           try  
           {  
                return SkillDALobj.GetEmpSkillData();  
           }  
           catch  
           {  
                throw;  
           }  
      }  
      public int InsertSkill(EmpSkillCls objSkillCls)  
      {  
           try  
           {  
                return SkillDALobj.InsertEmpSkill(objSkillCls);  
           }  
           catch  
           {  
                throw;  
           }  
      }  
      public int UpdateSkill(EmpSkillCls objSkillCls)  
      {  
           try  
           {  
                return SkillDALobj.UpdateEmpSkill(objSkillCls);  
           }  
           catch  
           {  
                throw;  
           }  
      }  
      public int DeleteSkill(EmpSkillCls objSkillCls)  
      {  
           try  
           {  
                return objSkillDAL.DeleteEmpSkill(objSkillCls);  
           }  
           catch  
           {  
                throw;  
           }  
      }  
 }  
 ===========  
 data acess layer  
 public class EmpSkillDAL  
 {  
      SqlConnection conn = new SqlConnection("your connection string");  
      DataSet Ds = new DataSet();  
      public DataSet GetEmpSkillData()  
      {  
           Ds = SqlHelper.ExecuteDataset(conn, "sp_SelectDelete");  
           return Ds;  
      }  
      public int InsertEmpSkill(EmpSkillCls Emp)  
      {  
           try  
           {  
                int Insert = SqlHelper.ExecuteNonQuery(conn, "usp_EmpSkillMasterAddEdit", Emp.SkillId, Emp.Skill);  
                return Insert;  
           }  
           catch  
           {  
                throw;  
           }  
           finally  
           {  
                conn.Close();  
           }  
      }  
      public int UpdateEmpSkill(EmpSkillCls emp)  
      {  
           try  
           {  
                int Result = SqlHelper.ExecuteNonQuery(conn, "usp_EmpSkillMaster_AddEdit", Emp.SkillId, Emp.Skill);  
                return Result;  
           }  
           catch  
           {  
                throw;  
           }  
           finally  
           {  
                conn.Close();  
           }  
      }  
      public int DeleteEmpSkill(EmpSkillCls emp)  
      {  
           try  
           {  
                int result = SqlHelper.ExecuteNonQuery(conn, "usp_EmpSkillMasterSelect", emp.SkillId);  
                return result;  
           }  
           catch  
           {  
                throw;  
           }  
           finally  
           {  
                conn.Close();  
           }  
      }  
 }  

Onclick Gridview Select button fill all the data to textbox.

 Onclick Gridview Select button fill all the data to textbox.  
 All the textbox out of gridview.  
 protected void ImgSelect_Click(object sender, ImageClickEventArgs e)  
 {  
      ImageButton aspSender = sender as ImageButton;  
      Label Id = aspSender.FindControl("lblContId") as Label;  
      hdnId.Value = Id.Text;  
      DataSet dsContact = new DataSet();  
      dsContact = SqlHelper.ExecuteDataset(connectionString, "usp_GetContact", Convert.ToInt32(Id.Text.Trim()), EmpId, "S");  
      if (dsContact.Tables[0].Rows.Count != 0)  
      {  
           txtName.Text = dsContact.Tables[0].Rows[0]["Name"].ToString();  
           ddlRelation.SelectedValue = dsContact.Tables[0].Rows[0]["RelId"].ToString();   
           txtAddress.Text = dsContact.Tables[0].Rows[0]["Address"].ToString();  
      }  
 }  

Sunday, September 5, 2010

Gridview RowCommand

If you hav any button inside Gridview you handle that button under RowCommand like here Gridview have a Insert button inside Grid.

 protected void gvStuDetails_RowCommand(object sender, GridViewCommandEventArgs e)  
{
if (e.CommandName.Equals("Insert"))
{
objStuCls.StuId = Convert.ToInt32(((DropDownList)gvStuDetails.FooterRow.FindControl("ddlNewStuId")).SelectedValue);
objStuCls.StuName = Convert.ToString(((TextBox)gvStuDetails.FooterRow.FindControl("txtNewStuName")).Text);
try
{
int int = objClassMasterBLL.InsertClassMaster(objStuCls);
if (int > 0)
{
msgText = "Record Added Successfully !";
gvStuDetails.EditIndex = -1;
gvStu();
}
else
{
msg.Text = "This record already exists !";
}
}
catch (Exception ee)
{
msg.Text = ee.Message.ToString();
}
}
}

Thanks & Regards
Santosh

Saturday, August 28, 2010

GridView Edit:on clicking edit a new page should be open where user can update data

 GridView Edit:on clicking edit a new page should be open where user can update data  
 On clicking edit in GridView a new page should be open where user can update data. In this article i am explaining how to update record using GridView.When User Click edit button in GridView new page will be open where user can update record.in second page i have just find the data not wrriten the code for update.  
 Here also i have written code for delete record in GridView and if GridView has no record show message no record found.  
 First Page code  
 public void GridViewBind()  
 {  
      using (SqlConnection conn = new SqlConnection(conStr))  
      {  
           DataSet ds = SqlHelper.ExecuteDataset(conn, "LeaveMaster_Select");  
           GridView1.DataSource = ds.Tables[0];  
           GridView1.DataBind();  
      }  
 }  
 protected void ImgDelete_Click(object sender, ImageClickEventArgs e)  
 {  
      ImageButton img = (ImageButton)sender;  
      Label Leave = img.FindControl("Label1") as Label;  
      using (SqlConnection conn = new SqlConnection(conStr))  
      {  
           conn.Open();  
           using (SqlTransaction t = conn.BeginTransaction())  
           {  
                try  
                {  
                     exceptionMessage.Text = SqlHelper.ExecuteScalar(t, "LeaveMaster_Delete", Leave.Text, "", 'D').ToString();  
                     t.Commit();   
                     GridViewBind();  
                }  
                catch  
                {  
                     t.Rollback();  
                }  
           }  
           conn.Close();  
      }  
 }   
 protected void ImgbtnDetails_Click(object sender, ImageClickEventArgs e)  
 {  
      //Selecting a Record from Grid For Updation..  
      ImageButton aspSender = sender as ImageButton;  
      Label lblId = aspSender.FindControl("lblLeaveID") as Label;  
      Response.Redirect("~/LeaveDetails.aspx?Id=" + lblId.Text + "");   
 }  
 ===========  
 2nd page  
 if (Request.QueryString["Id"] != null)  
 {  
      Id = Convert.ToInt32(Request.QueryString["Id"].ToString());  
      string str = "SELECT LeaveCode, LeaveDesc, LeaveId FROM LeaveMaster WHERE (LeaveId = "+Id+")";  
      DataTable dt1 = SqlHelper.ExecuteDataset(conStr, CommandType.Text, str).Tables[0];  
      txtCode.Text = dt1.Rows[0]["LeaveCode"].ToString();  
      txtCode.Enabled = false;  
      txtShortName.Text = dt1.Rows[0]["LeaveDesc"].ToString();  
      txtShortName.Enabled = false;   
 }  
 aspx Page  
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="LeaveId" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"   
 Width="700px" PageSize="10" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" >  
      <Columns>  
           <asp:TemplateField HeaderText="LeaveId" InsertVisible="False" SortExpression="LeaveId" Visible="False">  
                <EditItemTemplate>  
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("LeaveId") %>'></asp:Label>  
                </EditItemTemplate>  
                <ItemTemplate>  
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("LeaveId") %>'></asp:Label>  
                </ItemTemplate>  
           </asp:TemplateField>  
           <asp:BoundField DataField="LeaveCode" HeaderText="Leave Code" SortExpression="LeaveCode" />  
           <asp:BoundField DataField="LeaveShortDesc" HeaderText="Short Desc" SortExpression="LeaveShortDesc" />  
           <asp:BoundField DataField="LeaveLongDesc" HeaderText="Long Desc" SortExpression="LeaveLongDesc" />  
           <asp:CommandField ButtonType="Image" HeaderText="Edit" SelectImageUrl="~/Image/img_edit.png" ShowSelectButton="True">  
           <ItemStyle HorizontalAlign="Center" />  
           </asp:CommandField>  
           <asp:TemplateField HeaderText="Details">  
                <EditItemTemplate>  
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
                </EditItemTemplate>  
                <ItemStyle HorizontalAlign="Center" Width="40px" />  
                <ItemTemplate>  
                <asp:ImageButton ID="ImgbtnDetails" runat="server"   
                OnClick="ImgbtnDetails_Click" />  
                </ItemTemplate>  
           </asp:TemplateField>  
           <asp:TemplateField HeaderText="Delete">  
                <ItemTemplate>  
                <asp:ImageButton ID="imgbtnDelete" runat="server"   
                OnClick="ImgDelete_Click" OnClientClick="return ConfirmDelete();" />  
                </ItemTemplate>  
                <ItemStyle HorizontalAlign="Center" Width="50px" />  
           </asp:TemplateField>  
      </Columns>  
      <EmptyDataTemplate>No record found !</EmptyDataTemplate>  
 </asp:GridView>  

Tuesday, August 24, 2010

Nested GridView in asp.net using C#

 Nested GridView in asp.net using C#  
 Gridview within another gridview  
 This exmaple show how we can nest gridview.GridView inside other gridview for disply related data from database.Gridview can be nested in other Gridview control to display the related data of any item retrieved from database using C# code.  
 Steps:  
 1. Drag & drop a gridview in to the page.  
 2. Add a new template column to this gridview.  
 3. Place another gridview inside this template column.  
 <asp:GridView ID="GridView2" runat="server" EnableTheming="False" PageSize="15" Width="700px"  
 OnPageIndexChanging="GridView2_PageIndexChanging" OnRowDataBound="GridView2_RowDataBound"  
 AutoGenerateColumns="False">  
 <Columns>  
 <asp:TemplateField HeaderText="Employee Details">  
      <ItemTemplate>  
           <table>  
                <tr>  
                     <td>Company Name </td>  
                     <td>:</td>  
                     <td colspan="4"><asp:Label ID="lblCompany" runat="server" Text='<%# Bind("Company") %>'></asp:Label></td>                 
                </tr>  
                <tr>  
                     <td>Date</td>  
                     <td>:</td>  
                     <td colspan="4"><asp:Label ID="lblDate" runat="server">  
                </tr>  
           <tr>  
           <td colspan="6">  
                <asp:GridView ID="GridView1" runat="server" AllowPaging="True" EnableTheming="False"  
                PageSize="10" Width="100%" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False">  
                <Columns>   
                     <asp:BoundField DataField="User Name" HeaderText="Name">  
                     <ItemStyle HorizontalAlign="Left" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="LoanName" HeaderText="Loan">  
                     <ItemStyle HorizontalAlign="Left" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="Show Name" HeaderText="Payroll Month">  
                     <ItemStyle HorizontalAlign="Left" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="PDate" HeaderText="Paid Date">  
                     <ItemStyle HorizontalAlign="Center" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="OpeningBalance" HeaderText="Open Date">  
                     <ItemStyle HorizontalAlign="Right" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="PaidAmount" HeaderText="Amt. Paid">  
                     <ItemStyle HorizontalAlign="Right" >  
                     </asp:BoundField>   
                </Columns>  
                <RowStyle CssClass="reporttext" />  
                <EmptyDataTemplate>  
                <strong><span style="font-size: 10pt;">No Records....!</span> </strong>  
                </EmptyDataTemplate>  
                <PagerStyle CssClass="reportheader" />  
                <HeaderStyle CssClass="reportheader" Width="80px" />  
                <AlternatingRowStyle CssClass="reporttext" />  
                </asp:GridView>  
           </td>  
           </tr>   
           </table>  
      </ItemTemplate>  
 </asp:TemplateField>  
 </Columns>   
 </asp:GridView>  
 .cs code  
 protected void FirstGridBind()  
 {  
      DataTable dt1DataTable = new DataTable();  
      dt1.Columns.Add("CompanyName");  
      DataRow drDataRow = dt1DataTable.NewRow();  
      if (ddlCompany.SelectedValue != "0")  
      {  
           drDataRow["CompanyName"] = ddlCompany.SelectedItem.Text;  
      }  
      else  
      {  
           drDataRow["CompanyName"] = "All Companies";  
      }  
      dt1DataTable.Rows.Add(drDataRow);  
      GridView2.DataSource = dt1DataTable;  
      GridView2.DataBind();  
 }  
 protected void SecondGridBind()  
 {  
      foreach (GridViewRow row in GridView2.Rows)  
      {  
           Label lblDate = row.FindControl("lblDate") as Label;  
           if (txtFromDate.Text.Trim() != "" && txtToDate.Text.Trim() != "")  
           {  
                lblDate.Text = txtFromDate.Text.Trim() + " - " + txtToDate.Text.Trim();  
           }  
           else  
           {  
                lblDate.Text = "All Dates";  
           }  
           GridView GridView1 = row.FindControl("GridView1") as GridView;  
           string str = @"SELECT You query;  
           if (ddlCompany.SelectedValue != "0")  
           {  
           str += " AND (hrdEmployeeMaster.CompanyId = " + Convert.ToInt32(ddlCompany.SelectedValue) + ")";  
           }   
           DataTable dt = SqlHelper.ExecuteDataset(connString, CommandType.Text, str).Tables[0];  
           Session["myDataTable"] = dt;  
           GridView1.DataSource = dt;  
           GridView1.DataBind();  
           if (GridView1.Rows.Count > 0)  
           {  
           lbExport.Visible = true;   
           }  
      }  
 }  
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
 {  
      if (e.Row.RowType == DataControlRowType.DataRow)  
      {  
           if (GridView2.Rows.Count > 0)  
           {  
                GridView GridView1 = GridView2.Rows[0].FindControl("GridView1") as GridView;  
                e.Row.Cells[0].Text = Convert.ToString(GridView1.PageIndex * GridView1.PageSize + SrNo);  
                SrNo++;  
           }  
      }  
 }  

Tuesday, March 30, 2010

Validate GridView textbox in clientside using javascript

 Find Gridview TextBox in client side using javascript  
 Here this article show show how we can find gridview textbox which is inside Template Field and validate the entry while
editing the record.  
 function ValidateGridEditMode()  
 {  
      var n = document.getElementById('ctl00_ContentPlaceHolder1_tbcLocation_tpnlCountry_gvEmp').rows.length;  
      var i;  
      for(i=2; i <=n; i++)  
      {   
           if(i<10)  
           {  
                txtEmpName=document.getElementById('ctl00_ContentPlaceHolder1_tbcLocation_tpnlCountry_gvEmp_ctl0'+i+'_txtEmpName');   
           }  
           else  
           {  
                txtEmpName=document.getElementById('ctl00_ContentPlaceHolder1_tbcLocation_tpnlCountry_gvEmp_ctl'+i+'_txtEmpName');   
           }  
           if(txtEmpName !=null)  
           {  
                if(txtEmpName.value == "")  
                {  
                     alert("Enter Emp Name...!");   
                     txtEmpName.focus();   
                     return false;  
                }   
           }   
      }  
      return true;  
 }