Wednesday 17 September 2014

Dictionary(Generics) in c# asp.net | example and output

In this article i am going to show how to use generics using dictionary .
basically dictionary uses key value pair to display record.
we can add , remove , insert data in dictionary using key / value pair .
but this is that you need to  follow some rules.


To declare or define dictionary is

Dictionary <string , Int32> myFirstdictionary=new Dictionary<string,int>();


here my dictionary name is myFirstdictionary.
where i m pasing key as string and value will be int32,
now to add value in data using key we use key and pair value.
like this...

myFirstdictionary.Add("dev", 1);

where "dev" is string
and 1 is value type of  int.


Now to fetch data fromdictionary row by row we need to use for or foreach loop.


foreach(KeyValuePair<string, Int32> keys in myFirstdictionary)
        {
            Response.Write(keys.Key +"/"+ keys.Value + "<br/>");

        }



it will print data like this as printed below.





Monday 15 September 2014

List(Generic) | DataTable | Bind Gridview with examples

In this article i amGgoing to show how to create temporary table and fetch data in list to perform generics process and later on to bind Gridview. with examples.

   private void Genericswithtable()
    {
        DataTable temporarytableDt = new DataTable();
        temporarytableDt.Columns.Add("Id");
        temporarytableDt.Columns.Add("Name", typeof(String));
        temporarytableDt.Columns.Add("Email", typeof(String));
        temporarytableDt.Rows.Add(1, "dev", "dev@cxom");
        temporarytableDt.Rows.Add(2, "deva", "deva@cxom");

//created temporary table  so here  i am not  using any sql server connection just created
temporary table for example.

   
     
        List<string> listtable = new List<string>();
Declaration of list type string
     

        for (int i = 0; i < temporarytableDt.Rows.Count;i++)
        {
            listtable.Insert(i, temporarytableDt.Rows[i]["Name"].ToString() + 
                " / " + temporarytableDt.Rows[i]["Email"].ToString());
            
        }
//untill there will be rows in table all rows value will be inserted in List 
        //listtable.RemoveAt(1);
        listtable.Insert(2, "Raj");
        listtable.Add("Raja");
//Now here we can add more value wchich will appear after table value will be displayed.

        gridlist.DataSource = listtable;
        gridlist.DataBind();
//now we bind list to gridview there are many ways to take table value in list but this was simple method .
no need to create class or implement any kind of interface.
    }




Generics in c# with examples | Generics demo

Generics are type safe because there is no boxing and unboxing so
i will take  single datatype not heterogeneous like array list
so execution will be faster compare to collections.
Just we need to import System.collection.generics;


 private void PrivateGenerics()
    {
        List<int> newlist = new List<int>(); //declaring generics type int
        newlist.Add(3); // adding values
        //newlist.Add("5"); //will give compile time error;
        newlist.Add(2);
        int i = Convert.ToInt32("5"); 
        newlist.Add(i);
        newlist.Insert(0, 7); // giving index for in flow.
        newlist.Insert(1, 900000001);
        newlist.Insert(2, 900000002);
        newlist.Add(20);
        foreach (int myValue in newlist)
        {
            Response.Write(myValue +"<br/>");
        }

    }


 newlist.Sort();
        foreach (int myValue in newlist)
        {
            Response.Write(myValue +"<br/>");
        }
Generics With Array List .here i have shown how to add your arrayList in List<type int>
.

ArrayList Myarlist = new ArrayList();
        Myarlist.Insert(0, 40);
        Myarlist.Insert(1, 45);
        //Myarlist.Insert(2, "raj");
        var list = Myarlist.Cast<int>().ToList();//to add arraylist in list
        newlist.InsertRange(3, list);
        foreach (int myValue in newlist)
        {
            Response.Write(myValue +"<br/>");
        }


Now last code we added int value in array List so it works Fine.
Now we are going to add one string value in ArrayList And then See what would be
result.will it gives result or  there will be error.
Its showing Error because we have done casting of Arraylist to
integer type but we are providing String value also.


How to Bind Gridview using ArrayList in C# | Bind DropDown list

In This Article I am going to show You How to Bind GridView with Array List using Datatable and multidimensional array.

to bind dropdown
 string[,] mularray = {

                    { "Dev", "0001","6" },

                    { "Raj", "0003" ,"7"},

                    { "Tirth", "0004" , "8"},

                 };
   ArrayList arrList = new ArrayList();
            for (int i = 0; i < mularray.GetLength(0); i++)
            {
               
                arrList.Add(new ListItem(mularray[i, 0], mularray[i, 2]));
               
            }

            ddlp.DataSource = arrList;
            ddlp.DataTextField = "text";
            ddlp.DataValueField = "value";
            ddlp.DataBind();


lets have a code to bind Gridview using simple table which will swap in table and bind gridview.





            ArrayList MyarrayList = new ArrayList();
            DataTable temporarytableDt = new DataTable();
            temporarytableDt.Columns.Add("Id");
            temporarytableDt.Columns.Add("Name", typeof(String));
            temporarytableDt.Columns.Add("Email", typeof(String));
            temporarytableDt.Rows.Add(1, "dev", "dev@cxom");
            temporarytableDt.Rows.Add(2, "deva", "deva@cxom");
          



.cs code


        
            for (int i = 0; i < temporarytableDt.Rows.Count; i++)
            {
                string strbinfval = temporarytableDt.Rows[i]["Name"].ToString();
                MyarrayList.Insert(Convert.ToInt32(temporarytableDt.Rows[i]["Id"]) - 1,               

temporarytableDt.Rows[i]["Name"].ToString());
              
            }
            grdarraylist.DataSource = temporarytableDt;
            grdarraylist.DataBind();


.aspx code.


<div>
    <asp:GridView runat="server"  ID="grdarraylist" AutoGenerateColumns="false"    Caption = "Bind Grid With  Table"

Width="400px">
    <AlternatingRowStyle BackColor ="ActiveBorder" BorderColor="ActiveCaption" VerticalAlign="Middle"
   />
   <Columns>
 
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Email" HeaderText="Email" />


   </Columns>
   </asp:GridView>
    </div>


now i wanted to bind gridview using multidimensional or two dimensional array.


.cs page

 string[,] mularray = {

                    { "Dev", "0001","6" },

                    { "Raj", "0003" ,"7"},

                    { "Tirth", "0004" , "8"},

                 };
            ArrayList arrList = new ArrayList();
            for (int i = 0; i < mularray.GetLength(0); i++)
            {
              
                arrList.Add(new ListItem(mularray[i, 0], mularray[i, 2]));
            }
            grid.DataSource = arrList;
            grid.DataBind();


just fetched data into dimensional array and added in array list.

.aspx page
<asp:GridView runat="server"  ID="grid" AutoGenerateColumns="false"  Caption = "Bind Grid With  ArrayList" Width="400px">
    <AlternatingRowStyle BackColor ="ActiveBorder" BorderColor="ActiveCaption" VerticalAlign="Middle"/>
   <Columns>
  

<asp:BoundField DataField="Text" HeaderText="Id" />
<asp:BoundField DataField="Value" HeaderText="Name" />
   </Columns>
    </asp:GridView>




ArrayList in c# with examples

How to use arraylist in c#.
theses are basically collection so we need to import system.Collection;

Then to add array and array list

Here i have shown the code and examples to include array list in ur application.


private void arraylistdefault()
    {
        ArrayList myValue = new ArrayList { "MyFirstValue", "2", "3" };

        int indexofmyva = myValue.IndexOf("MyFirstValue");
      //  Response.Write(indexofmyva);//to get index of  MyFirstValue string
        //myValue.RemoveAt(indexofmyva); //to to removce  MyFirstValue
        //using Index
        myValue.Insert(3, "Third Value"); // inserting Third Value string
        myValue.Insert(4, "insert4");
        myValue.Add("add5");
        string[] ek = { "5col-name", "6-col-name" }; //adding range
        //it will insert 5col-name at 6 th position and 6-col-name at 6th position

        //myValue.Remove("added5"); //will remove  string added5
        //myValue.RemoveAt(3); will remove word which occupies value of index number 3;
     
        myValue.InsertRange(5,ek);
        myValue.Insert(7, "addedT7");
        myValue.RemoveAt(6); // will remove index 6th value
        myValue.Insert(6, ">new"); // will add >new string on 6th  position
        myValue.SetRange(7, ek);
        myValue.GetRange(3, 2);
        //myValue.Add(3); //Unable to cast object of type 'System.Int32' to type 'System.String'.

     
     even we can add int type data but we need to do casting like boxing and unboxing.

            foreach(string strvalue in myValue)
            {
                Response.Write(strvalue +"<br/>");
            }
    }

Now add array in array List.


Now here we are going to take int string value and wanted to convert in integer .
ArrayList new_array = new ArrayList(); 
new_array.AddRange(mystrarray); 
int forty = Convert.ToInt32("40"); 
new_array.Add(forty);

Thursday 28 August 2014

Export Datatable value to Excel in asp.net c#

Hi Everyone in this article  have shown how to export data table value in excel .
basically I don't have ms office installed so i  have opened with browser.
basically that is html table i  am generating but because i have given .xls extension so we can open it in
excel also.

so whatever e column u have included in stored procedure will come in report.
just pass data table value or rows and any file name so it will take all rows from table and convert them into
html format so we can open in excel also.
lets have a look.

 On buttonclick it will export
protected void btnExport_Click(Object sender, EventArgs e)
    {
     
        ExportDataToExcelUsingDataTable((DataTable)ViewState["table"], "Report For User" + DateTime.Now.ToShortDateString() + ".xls");

    }


function to convert datatable record or data to excel format like 
public void ExportDataToExcelUsingDataTable(DataTable DtRecordOfUser, string FlNm)
    {
        try
        {
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + FlNm);
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            string tab = string.Empty;

            HttpContext.Current.Response.Write("<table width='100%' border='1' " + "cellSpacing='0' cellPadding='0' " +


"style='font-size:11.0pt;'> <tr style='font-size:12pt;'>");


            for (int j = 0; j < DtRecordOfUser.Columns.Count; j++)

            {

                HttpContext.Current.Response.Write("<td  style='background-color:#339999;color:#FFF878;'>");

                HttpContext.Current.Response.Write("<B>");
                HttpContext.Current.Response.Write(DtRecordOfUser.Columns[j].ColumnName.ToString());
                HttpContext.Current.Response.Write("</B>");
                HttpContext.Current.Response.Write("</td>");
            }
            HttpContext.Current.Response.Write("</tr>");
            foreach (DataRow row in DtRecordOfUser.Rows)
            {

                HttpContext.Current.Response.Write("<tr>");

                for (int i = 0; i < DtRecordOfUser.Columns.Count; i++)
                {
                    HttpContext.Current.Response.Write("<td  style='background-color:#FFFBD6;color:#333333;'>");
                    HttpContext.Current.Response.Write(row[i].ToString());
                    HttpContext.Current.Response.Write("</td>");
                }

                HttpContext.Current.Response.Write("</tr>");

            }
            

            HttpContext.Current.Response.Write("</table>");

            HttpContext.Current.Response.Write("</font>");
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
        catch (Exception ex)
        {
            
        }

    }



export to excel using table



Wednesday 27 August 2014

Generate Dynamic table in html format in .cs page | Table Report | Design Report in asp.net with c#

Hi Everyone  in this article i am going to show how to generate dynamic table or we can say clone of grid view
with code behind .
we dont need to add any new control just apply css on code behind page and generate table with data.
i have shown both example with grid view and aslo with dynamic generated table with examples code.


0-> declare public string strDisplayDynamicTableReport = ""; before page load
1-> to take public string so we can assign string and then append on .aspx page like server control.
2-> We can bind our declare css also.
strDisplayDynamicTableReport += "<table cellpadding='0' cellspacing='0' border='1' bordercolor='red' >";
3->count table rows

for (int cnt = 0; cnt < DtGetAllEmoRecord.Rows.Count; cnt++)

4-> while  there is record in table add record in string and then print in html format.
by adding .aspx page

             <div>

                        <%=strDisplayDynamicTableReport%>

                  </div>


code for gridview


<asp:GridView runat="server" ID="grddata" AllowPaging="True" AutoGenerateColumns="false" DataKeyNames="NAME">
      <Columns>
          <asp:BoundField DataField="NAME" HeaderText="Name" ReadOnly="True"
              SortExpression="NAME" />
               <asp:BoundField DataField="NUMBER" HeaderText="Number" ReadOnly="True"
              SortExpression="NUMBER" />
               <asp:BoundField DataField="MAIL" HeaderText="Email Id" ReadOnly="True"
              SortExpression="MAIL" />
              <asp:TemplateField HeaderText="Delete">
              <ItemTemplate>
              <asp:LinkButton runat="server" ID="lnkdele" Text="delete" OnClick="lnkdele_click"></asp:LinkButton>
              </ItemTemplate>
              </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit">
              <ItemTemplate>
              <asp:LinkButton runat="server" ID="lnkedit" Text="Edit" OnClick="lnkedit_click"></asp:LinkButton>
              </ItemTemplate>
              </asp:TemplateField>
      </Columns>
      <EmptyDataRowStyle BackColor="#FF9999" BorderStyle="Dashed" />
     
    </asp:GridView>



just call below function on page load or any control event..




private void DiplayAllREcord()
    {
       
        SqlDataAdapter sda = new SqlDataAdapter("Sp_InsertUpadetData 'SELECT','','','',''", sqcon);
        DataTable DtGetAllEmoRecord = new DataTable();
        sda.Fill(DtGetAllEmoRecord);
      
       if (DtGetAllEmoRecord != null && DtGetAllEmoRecord.Rows.Count > 0)
        {
            strDisplayDynamicTableReport += "<div id='UserDetails'>";
            strDisplayDynamicTableReport += "<table cellpadding='0' cellspacing='0' border='1' bordercolor='red' >";
            strDisplayDynamicTableReport += "<tr>";
            strDisplayDynamicTableReport += "<td width='150'><b>Employee Name:</b> </td>";
            strDisplayDynamicTableReport += "<td width='150'><b>Employee Number:</b> </td>";
            strDisplayDynamicTableReport += "<td width='150'><b>Employee Email:</b> </td>";
            strDisplayDynamicTableReport += "</tr>";
            for (int cnt = 0; cnt < DtGetAllEmoRecord.Rows.Count; cnt++)
            {
              
                strDisplayDynamicTableReport += "<tr>";
                strDisplayDynamicTableReport += "<td width='200'>" + DtGetAllEmoRecord.Rows[cnt]["NAME"].ToString() + "</td>";
                strDisplayDynamicTableReport += "<td width='200'>" + DtGetAllEmoRecord.Rows[cnt]["NUMBER"].ToString() + "</td>";
                strDisplayDynamicTableReport += "<td width='200'>" + DtGetAllEmoRecord.Rows[cnt]["MAIL"].ToString() + "</td>";
                strDisplayDynamicTableReport += "</tr>";
               
            }
            strDisplayDynamicTableReport += "</table>";
            strDisplayDynamicTableReport += "</div>";
        }
        grddata.DataSource = DtGetAllEmoRecord;
        grddata.DataBind();
       
 
    }



how to merge row in gridview when value is same

hi guys in this article i am  going to show you how to merge rows in grid view it two rows has same value.
idea is very simple to check if next and previous rows has some equal data then merge that number of rows.using col span.

lets have a look.



Now here there is no mathing value now m entering one matching value.

now here is name and number is same for dev so after click on merge button we will merge both row in same row and other will in different column.
here is code

protected void btnExport_Click(Object sender, EventArgs e)
{

    MergeRows(grddata);

}

public void MergeRows(GridView gridView)
{
    for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
    {
        GridViewRow row = gridView.Rows[rowIndex];
        GridViewRow previousRow = gridView.Rows[rowIndex + 1];

        if (row.Cells[0].Text == previousRow.Cells[0].Text && row.Cells[1].Text == previousRow.Cells[1].Text)
        {
            row.Cells[0].RowSpan = (previousRow.Cells[0].RowSpan < 2) ? 2 : previousRow.Cells[0].RowSpan + 1;
            previousRow.Cells[0].Visible = false;
            row.Cells[1].RowSpan = (previousRow.Cells[1].RowSpan < 2) ? 2 : previousRow.Cells[1].RowSpan + 1;
            previousRow.Cells[1].Visible = false;
        }
    }
}

How to Export Gridview data in excel format in c# asp.net with example


Hi everyone in this article i am going to show you how to Export gridview  data into excel.

first thing is that you should have  Ms offices installed i don't have installed but i will show you in browser.


lets get the code which will fill the grid .i am using visual studio 2010 and database is Sql server 2008.


private void DiplayAllREcord()
    {
       
        SqlDataAdapter sda = new SqlDataAdapter("Sp_InsertUpadetData 'SELECT','','','',''", sqcon);
        DataTable DtGetAllEmoRecord = new DataTable();
        sda.Fill(DtGetAllEmoRecord);
        grddata.DataSource = DtGetAllEmoRecord;
        grddata.DataBind();

       
       }


this is my code to fill grid view before post back .
now my button to export code behind code

protected void btnExport_Click(Object sender, EventArgs e)
{
    ExportExcelusingGridview(grddata, "Report For User" + DateTime.Now.ToShortDateString() + ".xls");
}





now i have given code to export gridview data to excel  as i dont have  MS - office installed so i m going to show in browser.

public void ExportExcelusingGridview(GridView grd, string fileName)
    {
        StringBuilder sbDocBody = new StringBuilder(); ;
        try
        {


            if (grd.Rows.Count > 0)
            {


                sbDocBody.Append("<table width='100%' border='1' " + "cellSpacing='0' cellPadding='0' " +

"style='font-size:11.0pt;'> <tr style='font-size:12pt;'>");
                // Add Data Rows
                for (int j = 0; j < grd.HeaderRow.Cells.Count; j++)
                    sbDocBody.Append("<td style='background-color:#ECE9D8;color:#000000;' width=\"120\"><B>" +

grd.HeaderRow.Cells[j].Text + "</B></td>");
                sbDocBody.Append("</tr>");
                for (int i = 0; i < grd.Rows.Count; i++)
                {
                    sbDocBody.Append("<tr>");
                    for (int j = 0; j < grd.Rows[i].Cells.Count; j++)
                    {
                        sbDocBody.Append("<td style='background-color:#FFFFE8;color:#333333;'>" + grd.Rows[i].Cells[j].Text +

"</td>");
                    }
                    sbDocBody.Append("</tr>");
                }
                sbDocBody.Append("<tr>");
                for (int j = 0; j < grd.FooterRow.Cells.Count; j++)
                {
                    sbDocBody.Append("<td style='background-color:#ECE9D8;color:#fff;' width=\"120\"

style='text-align:left'>" + grd.FooterRow.Cells[j].Text + "</td>");
                }
                sbDocBody.Append("</tr>");
                sbDocBody.Append("</table>");

            }
            else
                sbDocBody.Append("No records to export !!");

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AppendHeader("Content-Type", "application/ms-excel");
            HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
            HttpContext.Current.Response.Write(sbDocBody.ToString());
            HttpContext.Current.Response.End();
        }
        catch (Exception ex)
        {
            //
        }
    }



so after click on excel it will appear like this..in browser but u can save it and if you need open with excel also.just copy code  ans paste it will work fine .just remember two things to include.
using System.Drawing;
using System.Text; //for string builder
using System.Web; // for httpcontext



Fetch all text box value into array

Fetch all text box value into array
hi everyone in this article i have shown how to fetch text box value or words or characters and use it like array
means to fetch all value which has entered in text  box and then restore each single value into array.


what i did i just took text box value into string and  had count length of string will be max array length so there be
no index-out of range  error will be come.

then using for loop count length and store each single value into array.
here is code



string  stringarrayvalue=Txtmytextboxvalue.text
        int[] aarr=new int [Txtmytextboxvalue.Text.Length];

//or u can take         int[] aarr=new int [stringarrayvalue.Length]; both will work




        for (int i = 0; i < stringarrayvalue.Length; i++)
        {


            aarr[i] =Convert.ToInt32(stringarrayvalue[i].ToString());

            Label lbli = new Label();

            lbli.Text = aarr[i].ToString();

            dvlabl.Controls.Add(lbli);

// took dynamic lable to display value
         



        }

this code is working fine.just copy and  paste  it .but label is dynamic u can take asp label.

how to generate dynamic controls text box , label in c# , asp.net.

how to  generate dynamic  controls text box , label in c# , asp.net.
how to  generate dynamic  controls text box , label in c# , asp.net.

in this article i have show how to generate dynamic control in asp.net and bind with existing control like Div .dynamic means

it will generate on run time .
first we will assign that attribute and then initialize new value .



To Generate Dynamic button
.cs page

    Button btnaddarray = new Button();
        btnaddarray.Text = "Add Array"; // Give text to respective button
        btnaddarray.ID = "BtnaddArray";   // provide id
        btnaddarray.Attributes.Add("Onclick", "BtnaddArray_Onclick"); // add event means when buton click  then event will be raised.



Now here i have called FunArray() function to generate dynamic controls in c# .
just copy or read this code and execute it.

private void FunArray()
    {
        int[] myArray = new int[10];
         myArray[0]=1;
        myArray[2]=2;
        myArray[3] = 3;
      
        Label lblPrintarrayvalue = new Label();
        lblPrintarrayvalue.Text =Convert.ToString("Array One:-" + myArray[0] +"Array Two:-"+"</Br>"+ myArray[1]+"Array

Three:-"+ myArray[2]+"<br/>");
        dvlabl.Controls.Add(lblPrintarrayvalue);
        lblPrintarrayvalue.ForeColor= System.Drawing.Color.Red;
        Response.Output.Write(lblPrintarrayvalue.Text);
        Response.Output.Write("<p>Your total is ${0:F2}</p>", lblPrintarrayvalue.Text);
        Response.Write(String.Format("<p>Your total is ${0:F2}</p>", lblPrintarrayvalue.Text));
        TextBox txttakeval = new TextBox();
        txttakeval.ID = "txtval";
        Label lblenterarray = new Label();
        lblenterarray.Text = "Enter Array List";
        txttakeval.Attributes.Add("Runat", "Server");
        Button btnaddarray = new Button();
        btnaddarray.Text = "Add Array";
        btnaddarray.ID = "BtnaddArray";
        btnaddarray.Attributes.Add("Onclick", "BtnaddArray_Onclick");

        btnaddarray.Click += new EventHandler(this.BtnaddArray_Onclick);
        dvlabl.Controls.Add(lblenterarray);
        dvlabl.Controls.Add(txttakeval);
        dvlabl.Controls.Add(btnaddarray);
      
      
      
    }

  private void BtnaddArray_Onclick(object sender, EventArgs e)
    {
//        your code

     
    }

.aspx page

 <div runat="server" id="dvlabl">
  <asp:Button runat="server" ID="btnsubmit"  Text="Submit" OnClick="btnsubmit_onclick" ValidationGroup="nm" />

  <asp:TextBox runat=server ID=txt2ley></asp:TextBox>
  </div>

Tuesday 26 August 2014

Fetch msg from sql server to c# code behind using execute scalar with validation

hi Everyone in this article i have shown how to get string or message from sql sever and to

display in c# code behind page with using output parameter with Execute Scalar method with

Insert and update and delete with Gridview with .aspx and .cs code.


so we can use execute non query also but that will return only zero & 1.
so we have used Execute Scalar so we can fetch message which we have return in sql server.
i have also shown execution part in  code behind.



default.aspx page.


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Inert update and delete in gridview
    </h2>
  <div>
  <asp:Label runat="server" Text="Enter Name" style="width:290px;"></asp:Label><input type="text"  runat="server" id="inptnm" placeholder="Enter  name"/>
  <asp:RequiredFieldValidator  runat="server"  id="rqres" ControlToValidate="inptnm" Text="*" ValidationGroup="nm"   ForeColor="Red" InitialValue=""></asp:RequiredFieldValidator>
  </div>
  <div>
  <br />
  <asp:Label runat="server"  Text="Enter number"></asp:Label><input type="text" runat="server" id="txtnumber"  text="*" placeholder="Enter  number" maxlength="10"/>
  <asp:RequiredFieldValidator  runat="server"  id="RequiredFieldValidator1" ControlToValidate="txtnumber" Text="*" ValidationGroup="nm"   ForeColor="Red" InitialValue=""></asp:RequiredFieldValidator>
      <asp:CompareValidator ID="CompareValidator1" runat="server"
          ErrorMessage="Pleas Enter Integer" ControlToValidate="txtnumber"
          Operator="DataTypeCheck" Type="Integer" ValidationGroup="nm"></asp:CompareValidator>
 

  </div>

    <div>
  <br />
  <asp:Label ID="Label1" runat="server"  Text="Enter Email"></asp:Label><input type="text" runat="server" id="txtmail"  text="*" placeholder="Enter  Mail"/>

<asp:RequiredFieldValidator  runat="server"  id="RequiredFieldValidator2" ControlToValidate="txtmail" Text="*" ValidationGroup="nm"   ForeColor="Red" InitialValue=""></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator
                ID="RegularExpressionValidator1" runat="server"
            ErrorMessage="Please enter Proper address" ControlToValidate="txtmail"  ValidationGroup="nm"
           
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

 

  </div>
  <asp:Button runat="server" ID="btnsubmit"  Text="Submit" OnClick="btnsubmit_onclick" ValidationGroup="nm" />
  <br />
  <asp:GridView runat="server" ID="grddata" AllowPaging="True" AutoGenerateColumns="false" DataKeyNames="NAME">
      <Columns>
          <asp:BoundField DataField="NAME" HeaderText="Name" ReadOnly="True"
              SortExpression="NAME" />
               <asp:BoundField DataField="NUMBER" HeaderText="Number" ReadOnly="True"
              SortExpression="NUMBER" />
               <asp:BoundField DataField="MAIL" HeaderText="Email Id" ReadOnly="True"
              SortExpression="MAIL" />
              <asp:TemplateField HeaderText="Delete">
              <ItemTemplate>
              <asp:LinkButton runat="server" ID="lnkdele" Text="delete" OnClick="lnkdele_click"></asp:LinkButton>
              </ItemTemplate>
              </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit">
              <ItemTemplate>
              <asp:LinkButton runat="server" ID="lnkedit" Text="Edit" OnClick="lnkedit_click"></asp:LinkButton>
              </ItemTemplate>
              </asp:TemplateField>
      </Columns>
      <EmptyDataRowStyle BackColor="#FF9999" BorderStyle="Dashed" />
     
    </asp:GridView>
    <asp:HiddenField runat="server" ID="hdnval" />
    <asp:HiddenField runat="server" ID="hdngetid" />

</asp:Content>






using System;
using System.Web.UI;
using  System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Web.Configuration;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
   SqlConnection sqcon=new SqlConnection(WebConfigurationManager.ConnectionStrings["constr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack == true)
        {
            hdnval.Value = "I";
            DiplayAllREcord();
        }
    }

    protected void btnsubmit_onclick(object sender, EventArgs e)
    {

         try
        {
             SqlCommand cmd = new SqlCommand("Sp_InsertUpadetData", sqcon);
            cmd.CommandType = CommandType.StoredProcedure;
            if (hdnval.Value == "U")
            {
                cmd.Parameters.AddWithValue("@Action", "UPDATE");
                hdnval.Value = "I";
                btnsubmit.Text = "Submit";
            }
            else
            {
                cmd.Parameters.AddWithValue("@Action", "INSERT");
            }
            cmd.Parameters.AddWithValue("@name", inptnm.Value);
            cmd.Parameters.AddWithValue("@number", txtnumber.Value);
            cmd.Parameters.AddWithValue("@Mail", txtmail.Value);
            cmd.Parameters.AddWithValue("@Msg" ,"").Direction = ParameterDirection.Output; 
           
            object val;
                  sqcon.Open();

                val = cmd.ExecuteScalar();
               
                if (Convert.ToString(val) == "SU")
                {
                    //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "msg", "'" + "<script>alert('Data inseted succesfully');</script>");
                    Response.Write("<script>alert('Request Saved Successfully')</script>");
                   
                    inptnm.Value = "";
                    txtnumber.Value = "";
                    txtmail.Value = "";
                    DiplayAllREcord();
                }
                else
                {
                    Response.Write("<script>alert('Please Add Proper Data')</script>");
                    //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "msg", "'" + "<script>alert(Email id Exists);<script>");
                }

           
        }
        catch (Exception ex)
        { Response.Write (ex.ToString());}
        finally{
            sqcon.Close();
            sqcon.Dispose();
        }

    }
    private void DiplayAllREcord()
    {
       
        SqlDataAdapter sda = new SqlDataAdapter("Sp_InsertUpadetData 'SELECT','','','',''", sqcon);
        DataTable DtGetAllEmoRecord = new DataTable();
        sda.Fill(DtGetAllEmoRecord);
        grddata.DataSource = DtGetAllEmoRecord;
        grddata.DataBind();
    


    }

    protected void lnkdele_click(object sender, EventArgs e)
    {

        LinkButton lnkbtn = sender as LinkButton;
        //getting particular row linkbutton

        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;

        //getting userid of particular row
       
        string username =Convert.ToString(grddata.DataKeys[gvrow.RowIndex].Value.ToString());
      
      

        SqlCommand  sda = new  SqlCommand("Sp_InsertUpadetData 'Delete',"+username+",'','',''", sqcon);
        int del = 0;
        sqcon.Open();
        del = sda.ExecuteNonQuery();
        sqcon.Close();
        if (del > 0)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "'" + "<script>alert('REcored deleted Succesfully');</script>");
           
        }
       
        DiplayAllREcord();
    }
    protected void lnkedit_click(object sender, EventArgs e)
    {
        LinkButton lnkedit = sender as LinkButton;
        GridViewRow grrow = lnkedit.NamingContainer as GridViewRow;
        string strupdateval = Convert.ToString(grddata.DataKeys[grrow.RowIndex].Value.ToString());
        hdnval.Value = "U";
        hdngetid.Value = strupdateval.ToString();
        SqlDataAdapter sda = new SqlDataAdapter("Sp_InsertUpadetData 'EDIT',"+strupdateval.ToString()+",'','',''", sqcon);
        DataTable DtGetAllEmoRecord = new DataTable();
        sda.Fill(DtGetAllEmoRecord);
        inptnm.Value = DtGetAllEmoRecord.Rows[0]["NAME"].ToString();
        txtmail.Value = DtGetAllEmoRecord.Rows[0]["MAIL"].ToString();
        txtnumber.Value = DtGetAllEmoRecord.Rows[0]["NUMBER"].ToString();
        btnsubmit.Text = "Update";
      
    }
  
}

stored procedure


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

ALTER Procedure [dbo].[Sp_InsertUpadetData]
(
@Action varchar(20),
@name varchar(20),
@number  int ,
@Mail varchar(20),
@Msg varchar(20) out
)
AS
BEGIN
DECLARE @RETURN AS VARCHAR(20)
IF (@Action='INSERT')
    BEGIN
    IF EXISTS(SELECT @Mail FROM insertstudbvalue where MAIL=@Mail )
    BEGIN
    SET @Msg='ER'
    END
    ELSE
    BEGIN
    INSERT INTO insertstudbvalue VALUES(@name , @number, @Mail)
UPDATE insertstudbvalue SET NUMBER=@NUMBER , MAIL=@MAIL WHERE
NAME=@NAME
    SET @Msg='SU'
    END
SELECT @Msg
END
ELSE IF (@Action='SELECT')
BEGIN
SELECT NAME , NUMBER , MAIL FROM insertstudbvalue
END

ELSE IF (@Action='DELETE')
BEGIN
DELETE FROM insertstudbvalue WHERE  NAME=@NAME
END
ELSE IF (@Action='UPDATE')
BEGIN
   
    IF EXISTS(SELECT @Mail FROM insertstudbvalue where MAIL=@Mail And  NAME = @NAME)
    BEGIN
        UPDATE insertstudbvalue SET NUMBER=@NUMBER , MAIL=@MAIL WHERE
        NAME=@NAME
        SET @Msg='SU'
    END
    ELSE
    BEGIN
        IF EXISTS(SELECT @Mail FROM insertstudbvalue where MAIL=@Mail And  NAME <> @NAME)
            BEGIN
               
                SET @Msg='ER'
            END
    END
   
SELECT @Msg
END
ELSE IF (@Action='EDIT')
BEGIN
SELECT NAME , NUMBER , MAIL FROM insertstudbvalue WHERE
NAME=@NAME
END
END











Wednesday 2 April 2014

An unhandled exception of type 'SAP.Middleware.Connector.RfcCommunicationException' occurred in sapnco.dll

An unhandled exception of type 'SAP.Middleware.Connector.RfcCommunicationException' occurred in sapnco.dll

An unhandled exception of type 'SAP.Middleware.Connector.RfcCommunicationException' occurred in sapnco.dll
Additional information:
LOCATION    CPIC (TCP/IP) on local host with Unicode
ERROR       partner 'ipaddress' not reached

It shows the error you are getting just because of  you have entered wrong ip address in  sap connection with asp.net .
sometimes  we use web service to connect sap but sometimes just dll files at that time data you providing like ..
ip address , uname and password then you need to add correct information else you will get error  like that.

Unhandled Exception: System.TypeInitializationException: The type initializer for 'SAP.Middleware.Connector.RfcDestinationManager' threw an exception. ---> System.TypeInitializationException: The type initializer for 'SAP.Middleware.Connect or.RfcConfigParameters' threw an exception.

Unhandled Exception: System.TypeInitializationException: The type initializer for 'SAP.Middleware.Connector.RfcDestinationManager' threw an exception. ---> System.TypeInitializationException: The type initializer for 'SAP.Middleware.Connect or.RfcConfigParameters' threw an exception.
This  error comes when we have included sapnco and utills dll in  your  folder for sap connection with
asp.net in c# or vb.net.
so for that you do just one thing  put your exe file and dll files in same folder.
and run exe files it will works.definitely.because sapnco and utills dll are external dll
so you need to add in your folder so there will be connection between your exe file and dll files.
if you will try on your machine it won't give you error but when you deploy on another machine then you
can face this issue .so better to think before do anything.somewhere you will get answer to register
your  dll files in GAC but that will be different scenario.so , just add proper dll files and
in proper way sometimes it happens that connection you are trying is unreachable.
so , first of all just try to do connection and then  move ahead.

this was single error but   you can find another like..

Unhandled Exception: System.TypeInitializationException: The type initializer fo
r 'SAP.Middleware.Connector.RfcDestinationManager' threw an exception. ---> Syst
em.TypeInitializationException: The type initializer for 'SAP.Middleware.Connect
or.RfcConfigParameters' threw an exception. ---> System.IO.FileLoadException: Co
uld not load file or assembly 'sapnco_utils, Version=3.0.0.42, Culture=neutral,
PublicKeyToken=50436dca5c7f7d23' or one of its dependencies. The application has
 failed to start because its side-by-side configuration is incorrect. Please see
 the application event log for more detail. (Exception from HRESULT: 0x800736B1)


File name: 'sapnco_utils, Version=3.0.0.42, Culture=neutral, PublicKeyToken=5043
6dca5c7f7d23' ---> System.Runtime.InteropServices.COMException (0x800736B1): The
 application has failed to start because its side-by-side configuration is incor
rect. Please see the application event log for more detail. (Exception from HRES
ULT: 0x800736B1)
   at SAP.Middleware.Connector.RfcConfigParameters..cctor()


   --- End of inner exception stack trace ---
   at SAP.Middleware.Connector.RfcConfigParameters.Initialize()
   --- End of inner exception stack trace ---
   at SAP.Middleware.Connector.RfcDestinationManager.RegisterDestinationConfigur
ation(IDestinationConfiguration config)
   at RecruitmentSchedular.MainFunction.Main(String[] args)

How to solve Problem Event Name:CLR20r3 | Asp.net console application

How to solve Problem Event Name:CLR20r3 | Asp.net console application
Problem Event Name:    CLR20r3
this exception comes if you have missed something or forgot to in include in your folder .
like if you are working with sql server  then  you forgot to add stored procedure.
and when you have used console or window application to generate .exe file and uploaded on another computer
or another server.
so for that no need to worry about that just  check whatever files and functions you have uploade on your
 local machine and same thing you should include when you are
running your  exe file on another machine.but before that you need to know your exe file is working proper.

Wednesday 26 February 2014

How to find out day and year and month in respective date in sql server .2005 | sql server 2008.

How to find out day and year and month in respective date in sql server .2005 | sql server 2008.

we will see how can we find out day and month and year in given date separately .
to find out same we have to use DAY ,MONTH and YEAR keyword respectively which is by default or defined by sql server .
so no need to put some extra efforts.
just write same keyword after you use that keyword they will appear in pink colour in sql server.
lets look at examples.
suppose i have last date of submission my fee now i want to find  out day and month and year of lastdateofsubmission then i will
write like this.

for  day select DAY(LastSubmissionDate) from tableName
for month select MONTH(LastSubmissionDate) from tableName
for year  select Year(LastSubmissionDate) from tableName


now output will be
31 --day
2  --month
2014 --year


we can write in same line also..
select   DAY((LastSubmissionDate) ),MONTH ((LastSubmissionDate) ),YEAR ((LastSubmissionDate)  ) from tableNamewhere DueDate <> '' and DAY((LastSubmissionDate) ) in ('1','13','30')
which will gives you date which comes under day 1 , 13, 30 in every month and year.