insert into tblMonthMst
select * from EMPMain.[dbo].[tblMonthMst]
select * from EMPMain.[dbo].[tblMonthMst]
<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>
<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>
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", "<script>alert('Row deleted')</script>");
BindGridView();
}
}
}
}
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();
}
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>
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);
}
}
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 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
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.
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();
}
}
How to Store Multiple Value In Session using asp.net c#
We can add multiple values by using class entiry or hashtable or arralist:
Here a we will use Hashtable for storing multiple value in session
Hashtable htEmpInfo = new Hashtable();
htEmpInfo.Add("Name", "Santosh");
htEmpInfo.Add("Designation", "SE");
htEmpInfo.Add("Department", "MS");
session["EmpDetails"]=htEmpInfo;
Retrieving the values from the session
Hashtable htEmpInformaiton = (Hashtable)session["EmpDetails"];
lblEmopName.Text=htEmpInformaiton["Name"].ToString();
lblDesignation.Text=htEmpInformaiton["Designation"].ToString();
function valid(txt,maxLen,lbl1)
{
lbl1.innerText=(txt.value.length+1);
if(txt.value.length > (maxLen-1))
{
alert("Entered Text reach at its maximum size..!");
return false;
}
}
txtFeedback.Attributes["onkeypress"] = "return valid(this,500," + Label1.ClientID + ")";
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();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload fileUpload1 = ((FileUpload)(this.FindControl("fileUpload1")));
if (((fileUpload1.PostedFile == null) || (string.IsNullOrEmpty(fileUpload1.PostedFile.FileName) || (fileUpload1.PostedFile.InputStream == null))))
{
Label1.Text = "Please Upload Valid picture file";
return;
}
int len = fileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[len];
fileUpload1.PostedFile.InputStream.Read(pic, 0, len);
string extension = System.IO.Path.GetExtension(fileUpload1.PostedFile.FileName).ToLower();
string MIMEType = null;
switch (extension)
{
case ".gif":
MIMEType = "image/gif";
break;
case ".jpg":
case ".jpeg":
case ".jpe":
MIMEType = "image/jpeg";
break;
case ".png":
MIMEType = "image/png";
break;
default:
Label1.Text = "Not a Valid file format";
return;
break;
}
string fname = txtName.Text;
string lname = txtLName.Text;
string gender = rdGender.SelectedItem.Text;
string age = drpAge.SelectedItem.Text;
string state = txtState.Text;
SqlConnection myConnection;
myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConnectSan"].ToString());
SqlCommand myCommand = new SqlCommand("usp_InsertPersonDetail", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = fname;
myCommand.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = lname;
myCommand.Parameters.Add("@GenderID", SqlDbType.VarChar, 50).Value = gender;
myCommand.Parameters.Add("@Age", SqlDbType.VarChar, 50).Value = age;
myCommand.Parameters.Add("@MCA", SqlDbType.VarChar, 50).Value = str;
myCommand.Parameters.Add("@State", SqlDbType.VarChar, 50).Value = state;
myCommand.Parameters.Add("@MIMEType", SqlDbType.VarChar, 50).Value = MIMEType;
myCommand.Parameters.Add("@ImageData",SqlDbType.Image,16).Value = pic;
myCommand.Parameters.Add("@Length", SqlDbType.VarChar, 50).Value = len;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
msg.Text = "Record save successfully";
}
<asp:TextBox ID="txtusername" runat="server" ValidationGroup="Group1"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvUname" runat="server" ControlToValidate="txtusername"
ErrorMessage="Name is required." ValidationGroup="Group1">*</asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" Text="Save" ValidationGroup="Group1" />
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" ValidationGroup="Group2></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvpass" runat="server" ControlToValidate="txtPassword"
ErrorMessage="Password is required." ValidationGroup="Group2">*</asp:RequiredFieldValidator>
<asp:Button ID="btnSavePass" runat="server" Text="Save Password" ValidationGroup="Group2" />
public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
Console.WriteLine("Please select the convertor direction");
Console.WriteLine("1. From Celsius to Fahrenheit.");
Console.WriteLine("2. From Fahrenheit to Celsius.");
Console.Write(":");
string selection = Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
Console.WriteLine("Please select a convertor.");
break;
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
public class MyBaseClass
{
MyBaseClass()
{
}
public static void PrintName()
{
}
}
public class MyDerivedClass : MyBaseClass
{
MyDerivedClass ()
{
public void DoSomething()
{
MyBaseClass.GetName();
}
}
}
7. Can we use a static function with a non-static variable? public class CashSales
{
//declare static member field
private static int maxUnitsAllowed = 50;
//declare method to return maximum number of units allowed
public static int GetMaxUnitsAllowed ()
{
Return maxUnitsAllowed;
}
}
The static field can now be accessed by simply doing CashSales.GetMaxUnitsAllowed(). No need to create an instance of the class. public sealed class Singleton
{
static readonly Singleton Instance=new Singleton();
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return Instance;
}
}
}
30. What are virtual destructures? using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee: Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass {
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
35. What are the different.NET tools which you used in projects? DataSet dt=new DataSet("mydata");
mydata.Fill(dt,"mydata");
DataView myDataView = dt.Tables["mydata"].DefaultView ;
myDataView.Sort = "id DESC";
DataGrid1.DataSource=myDataView;
DataGrid1.DataBind();
Learning Technique for freshers : R3C2
1.RequiredFieldValidation Control
2.RangeValidator Control
3.RegularExpressionValidator Control
4.CompareValidator Control
5.CustomValidator Control
Properties of Validation Controls.
ControlToValidate - Id of control Which you want to validate.
ErrorMessage - Message that will be displayed in the validation summary.
IsValid - Whether or not the control is valid.
Validate - Method to validate the input control and update the IsValid property.
Display - How the error message will display.options are given below
None:Message is never displayed.
Static:Validation message will display in the page layout.
Dynamic:Validation message is dynamically added to the page if validation fails.
Example with code:
1.RequiredFieldValidation:It is simple validation control which checks data is entered or not.
<asp:textbox id="txtEmpName" runat="server"/>
<asp:RequiredFieldValidator id="rfvtxtbox" runat="server" ControlToValidate="txtEmpName"
ErrorMessage="* Please enter the employee name" Display="dynamic">*
</asp:RequiredFieldValidator>
2.RangeValidator:It checks to see if a control value is within a valid range or not.
<asp:textbox id="txtDOB" runat="server"/>
<asp:RangeValidator id="rangeVal" runat="server"
ControlToValidate="txtDOB1"
MaximumValue="12/06/2009"
MinimumValue="01/01/1983"
Type="Date"
ErrorMessage="* Please enter the valid date" Display="static">*</asp:RangeValidator>
3.RegularExpressionValidator:It can be used for email validation or any specified string based on pattern matching.
E-mail: <asp:textbox id="txtEmail" runat="server"/>
<asp:RegularExpressionValidator id="revemail" runat="server"
ControlToValidate="txtEmail"
ValidationExpression=".*@.*\..*"
ErrorMessage="* Please enter valid e-mail ."
display="dynamic">*
</asp:RegularExpressionValidator>
4.CompareValidator: It allows you to make comparisons between two form controls and also compare values contained with
these controls to constants that specified by userd.
New Password: <asp:textbox id="txtNewPass" runat="server"/><br />
Confirm Passowrd: <asp:textbox id="txtConfirmPass" runat="server"/><br />
<asp:CompareValidator id="valCompare" runat="server"
ControlToValidate="txtNewPass" ControlToCompare="txtConfirmPass"
Operator="Equals"
ErrorMessage="* New Password and confirm password are not same"
Display="dynamic">*
</asp:CompareValidator>
5.CustomValidator:It allows you to write your own server-side or client-side validations logic and it can be easily applied to your web forms controls.
<asp:CustomValidator ID="cv" runat="server"
ControlToValidate="txtName" ClientValidationFunction="customvalidationr"
ErrorMessage="Please enter correct name"></asp:CustomValidator>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" />
Client side javascript
<script type="text/javascript">
function customvalidation(oSrc,args)
{
write your code here
}
</script>