Tuesday, December 13, 2011

Convert to any Datetime format in c#

string StartDate = DateTime.Now.ToShortDateString();

string CStartDate = DateTime.ParseExact(CertStartDate, "dd/MM/yyyy",null).ToString("yyyy-MM-dd");


you can convert dd/MM/yyyy to any other format by specifiying like ToString("yyyy-MM-dd")

Thursday, September 1, 2011

StoredProcedure


//SP  with out parameter
//to create SP
CREATE PROCEDURE SP_TestNoParam

AS
BEGIN   
    SELECT * FROM TBL_Details
END   
   
//to drop SP  
 drop procedure SP_TestNoParam
 //to view SP
 sp_helptext SP_TestNoParam
 //to execute SP
 SP_TestNoParam

-------------------
//SP with parameters

CREATE PROCEDURE SP_Test(
                        @P_ID INT                       
                        )
    AS
    BEGIN
        SELECT * FROM TBL_Details WHERE ID=@P_ID
    END 

 SP_Test 2


-----------------------
//insert SP
CREATE PROCEDURE SP_TestInsert(                           
                            @P_Name VARCHAR(100),
                            @P_Age INT
                              )
AS
BEGIN
    DECLARE @P_ID INT
    SET @P_ID=(SELECT ISNULL(MAX(ID),0) FROM TBL_Details) + 1
    INSERT INTO TBL_Details VALUES(@P_ID,@P_Name,@P_Age)
END

//caling SP
SP_TestInsert 'Test123', 33
-----------------------------------
    public void DataConnectionSP(string query,string name,int age)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True;Pooling=False";
            con.Open();
            SqlCommand com = new SqlCommand();
            com.Connection = con;
            com.CommandText = query;
            com.Parameters.Add(new SqlParameter("@P_Name",name));
            com.Parameters.Add(new SqlParameter("@P_Age",age));
            com.CommandType = CommandType.StoredProcedure;

            com.ExecuteNonQuery();
        }

 -------------------------------

//In grid rowCommand put

string query = "SP_TestInsert";
oGridDL.DataConnectionSP(query,txtName.Text.ToString(),Convert.ToInt32(txtAge.Text));

Grid EmptyRow Fill

<Gridview>
<column>
</column>

 <EmptyDataTemplate>
            <table>
            <tr>
          
            <td><asp:Label ID="Label1" runat="server" Text="Name"></asp:Label></td>
            <td><asp:Label ID="Label2" runat="server" Text="Age"></asp:Label></td>
            <td><asp:Label ID="Label3" runat="server" Text="Place"></asp:Label></td>
            <td><asp:Label ID="Label4" runat="server" Text="Dob"></asp:Label></td>
             <td><asp:Label ID="Label6" runat="server" Text="Add"></asp:Label></td>
            </tr>
            <tr>
            <td><asp:TextBox ID="txtNameE" runat="server"></asp:TextBox></td>
            <td><asp:TextBox ID="txtAgeE" runat="server"></asp:TextBox></td>
            <td><asp:TextBox ID="txtPlaceE" runat="server"></asp:TextBox></td>
            <td><asp:TextBox ID="txtDOBE" runat="server" ></asp:TextBox></td>
            <td><asp:ImageButton runat="server" ID="imgAddE" ImageUrl="Images/add.gif" CommandName="InsertEmpty"/></td>
            </tr>
            </table>
            </EmptyDataTemplate>

</Gridview>

-----------------------------------

aspx.cs


 protected void gvwtest_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                TextBox txtName = gvwtest.FooterRow.FindControl("txtName") as TextBox;
                TextBox txtAge = gvwtest.FooterRow.FindControl("txtAge") as TextBox;
                TextBox txtPlace = gvwtest.FooterRow.FindControl("txtPlace") as TextBox;
                TextBox txtDOB = gvwtest.FooterRow.FindControl("txtDOB") as TextBox;
              

                string query = "INSERT INTO TBL_UserDetails VALUES((SELECT ISNULL(MAX(Id),0) as maxid FROM TBL_UserDetails)+1,'" + txtName.Text + "','" + txtAge.Text + "','" + txtPlace.Text + "','" + txtDOB.Text + "')";
                DataConnection(query, 0);
                FillUserDetails();
            }
            else if (e.CommandName == "InsertEmpty")
            {
                TextBox txtName = gvwtest.Controls[0].Controls[0].FindControl("txtNameE") as TextBox;
                TextBox txtAge = gvwtest.Controls[0].Controls[0].FindControl("txtAgeE") as TextBox;
                TextBox txtPlace = gvwtest.Controls[0].Controls[0].FindControl("txtPlaceE") as TextBox;
                TextBox txtDOB = gvwtest.Controls[0].Controls[0].FindControl("txtDOBE") as TextBox;

                string query = "INSERT INTO TBL_UserDetails VALUES((SELECT ISNULL(MAX(Id),0) as maxid FROM TBL_UserDetails)+1,'" + txtName.Text + "','" + txtAge.Text + "','" + txtPlace.Text + "','" + txtDOB.Text + "')";
                DataConnection(query, 0);
                FillUserDetails();
            }
        }




DisplayMessage Function in aspx

private void DisplayMessage(string strMsg)
  {
      string strScript = "<script langauge=javascript type=text/javascript> alert('" + strMsg + "')</script>";
      ClientScript.RegisterClientScriptBlock(this.GetType(), "", strScript);
  }

Wednesday, August 31, 2011

Grid RowDatabound and PageIndexing

protected void gvwtest_RowDataBound(object sender, GridViewRowEventArgs e)
 {
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
     ImageButton ibtnDelete = e.Row.FindControl("ibtnDelete") as ImageButton;
     ibtnDelete.Attributes.Add("onclick", "return(confirm('Are you sure you want to delete the Name?'))");
     }

 }




 protected void gvwtest_PageIndexChanging(object sender, GridViewPageEventArgs e)
  {
      gvwtest.PageIndex = e.NewPageIndex;
      FillGrid();
 }

Grid RowUpdate

 protected void gvwtest_RowUpdating(object sender, GridViewUpdateEventArgs e)
  {
      TextBox txtEditName = gvwtest.Rows[e.RowIndex].FindControl("txtEditName") as TextBox;
      if (txtEditName.Text == "")
     {
     DisplayMessage("Please Enter Name");
     return;
     }
     Test_Info oTest_Info = new Test_Info();
     ImageButton ibtnUpdate = gvwtest.Rows[e.RowIndex].FindControl("ibtnUpdate") as ImageButton;

     oTest_Info.Id = Convert.ToInt32(ibtnUpdate.CommandArgument);
     oTest_Info.Name = txtEditName.Text.Trim();
    
     Test_BL oTest_BL = new Test_BL();
     int Result=oTest_BL.UpdateName(oTest_Info.Id,oTest_Info.Name);
     if (Result == 1)
     {
     DisplayMessage("Updated successfully");
     }
     else
     {
     DisplayMessage("Same  Name Already Exist");
     }
     gvwtest.EditIndex = -1;
     FillGrid();
}

Grid RowEdit and CancelEdit

protected void gvwtest_RowEditing(object sender, GridViewEditEventArgs e)
{
    Label lblName = gvwtest.Rows[e.NewEditIndex].FindControl("lblName") as Label;
    gvwtest.EditIndex = e.NewEditIndex;
    FillGrid();
    TextBox txtEditName = gvwtest.Rows[e.NewEditIndex].FindControl("txtEditName") as TextBox;
    txtEditName.Text = lblName.Text;
}



protected void gvwtest_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
 {
     gvwtest.EditIndex = -1;
     FillGrid();
 }

Grid RowDelete


protected void gvwtest_RowDeleting(object sender, GridViewDeleteEventArgs e)
 {
     Test_BL oTest_BL = new Test_BL();
     ImageButton ibtnDelete = gvwtest.Rows[e.RowIndex].FindControl("ibtnDelete") as ImageButton;
     int Id = Convert.ToInt32(ibtnDelete.CommandArgument);
     oTest_BL.DeleteName(Id);
     FillGrid();
     DisplayMessage("Deleted Successfully");
 }

Grid RowCommand


protected void gvwtest_RowCommand(object sender, GridViewCommandEventArgs e)
{

    if (e.CommandName == "Insert")
    {
    TextBox txtName = gvwtest.FooterRow.FindControl("txtName") as TextBox;
    if (txtDepartmentName.Text == "")
    {
        DisplayMessage("Please Enter Name");
        return;
    }
    //create object from Bussiness layer
    Test_BL oTest_BL = new Test_BL();
    int maxid = oTest_BL.GetMaxId() + 1;
    lblMaxId.Text = maxid.ToString();
    lblMaxId.Visible = false;
   
    Test_Info oTest_Info = new Test_Info();
    oTest_Info.Id = Convert.ToInt32(lblMaxId.Text);

    oTest_Info.Name = txtName.Text.Trim();

       int Result = oTest_BL.insertName(oTest_Info.Id,oTest_Info.Name);

       if (Result == 1)
       {
       DisplayMessage("Saved successfully");
       }
       else
    {
        DisplayMessage("Same  Name Already Exist");
    }
   
    //Filling gridview once again after insert
    FillGrid();

    }

}

Fill Grid

protected void FillGrid()
{
    Test_BL oTest_BL = new Test_BL();
    DataSet Dts = oTest_BL.GetAllNames();
    if (Dts.Tables[0].Rows.Count == 0)
    {
    Dts.Tables[0].Rows.Add(Dts.Tables[0].NewRow());
    gvwtest.DataSource = Dts;
    gvwtest.DataBind();
    gvwtest.Rows[0].Visible = false;
    }
    else
    {
    gvwtest.DataSource = Dts;
    gvwtest.DataBind();
    }

}

Grid Operations

ASPX Page


<asp:GridView ID="gvwtest" runat="server" AutoGenerateColumns="false" Width="99%"
    ShowFooter="true" onrowcommand="gvwtest_RowCommand"
    onrowcancelingedit="gvwtest_RowCancelingEdit"
    onrowdeleting="gvwtest_RowDeleting"
    onrowediting="gvwtest_RowEditing"
    onrowupdating="gvwtest_RowUpdating"
    onrowdatabound="gvwtest_RowDataBound"
    onpageindexchanging="gvwtest_PageIndexChanging" PageSize="10"
    AllowPaging="True">   
                        <Columns>
                            <asp:TemplateField HeaderText="Sl No">
                                <ItemStyle HorizontalAlign="Center" Width="10%" />
                                <HeaderStyle HorizontalAlign="Center" />
                                <ItemTemplate>
                                    <%# Container.DataItemIndex + 1 %>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Name">
                                <ItemStyle HorizontalAlign="Left" Width="70%" />
                                <HeaderStyle HorizontalAlign="Left" />
                                <ItemTemplate>
                                    <asp:Label ID="lblName" Text='<%# Bind("fld_Name") %>' runat="server"></asp:Label>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:TextBox ID="txtName" runat="server" MaxLength="74" Width="50%"></asp:TextBox>
                                     <cc1:FilteredTextBoxExtender ID="txtName_FilteredTextBoxExtenderF" runat="server"
                                            Enabled="True" TargetControlID="txtName" FilterType="Custom" ValidChars="A,B,C,D,E,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,
                                            R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,1,2,3,4,5,6,7,8,9,0,.,-, ,_">
                                        </cc1:FilteredTextBoxExtender>
                                </FooterTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtEditName"  MaxLength="74" runat="server" Width="50%"></asp:TextBox>
                                     <cc1:FilteredTextBoxExtender ID="txtEditName_FilteredTextBoxExtenderF" runat="server"
                                            Enabled="True" TargetControlID="txtEditName" FilterType="Custom" ValidChars="A,B,C,D,E,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,
                                            R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,1,2,3,4,5,6,7,8,9,0,.,-, ,_">
                                        </cc1:FilteredTextBoxExtender>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField ShowHeader="true" HeaderText="Edit">
                                <ItemStyle HorizontalAlign="Center" Width="10%" />
                                <HeaderStyle HorizontalAlign="Center" />
                                <EditItemTemplate>
                                    <asp:ImageButton ID="ibtnUpdate" runat="server" CausesValidation="True" CommandName="Update"
                                        Text="Update" CommandArgument='<%#Eval("fld_Id") %>' ImageUrl="~/styles/update.gif">
                                    </asp:ImageButton>
                                    &nbsp;<asp:ImageButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                                        ImageUrl="~/styles/cancel.gif" Text="Cancel"></asp:ImageButton>
                                </EditItemTemplate>
                                <FooterTemplate>
                                    <center>
                                        <asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="False" CommandName="Insert"
                                            ImageUrl="~/styles/add.gif" />
                                    </center>
                                </FooterTemplate>
                                <ItemTemplate>
                                    <asp:ImageButton ID="ibtnEdit" runat="server" CausesValidation="False" CommandName="Edit"
                                        Text="Edit" CommandArgument='<%#Eval("fld_Id") %>' ImageUrl="~/styles/edit.gif">
                                    </asp:ImageButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField ShowHeader="true" HeaderText="Delete">
                                <ItemStyle HorizontalAlign="Center" Width="9%" />
                                <HeaderStyle HorizontalAlign="Center" />
                                <ItemTemplate>
                                    <asp:ImageButton ID="ibtnDelete" runat="server" CausesValidation="False" CommandName="Delete"
                                        CommandArgument='<%#Eval("fld_Id") %>' ImageUrl="~/styles/delete1.jpg"
                                        Text="Delete"></asp:ImageButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>