Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

How To Put Symbol Into Table In C#(ASP.Net)

Insert symbol into table in database isn't easy. There are many developer know about it. When I meet this problem I search a long time to find the way for completed this task. Finally I found the solution that very easy.

The solution just add some property in page design as code below:

<@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomerExtraField.aspx.cs" Inherits="System" ValidateRequest="false" %>

When you add this properties you will can insert symbol in table.

Create Dynamic AJAX Control - Calendar Extender

If you want to create Ajax Control Toolkit- Calendar Extender please follow
code below:

// Create a textbox to hold the date
TextBox dateValue = new TextBox();
dateValue.ID = "dateValue";

// Create the calendar extender
AjaxControlToolkit.CalendarExtender ajaxCalendar =
new AjaxControlToolkit.CalendarExtender();
ajaxCalendar.ID = "ajaxCalendar";
ajaxCalendar.Format = "MM/dd/yyyy";
ajaxCalendar.TargetControlID = dateValue.ID;

placeHolder1.Controls.Add(dateValue);
placeHolder1.Controls.Add(ajaxCalendar);

In the ASPX, I have just a simple PlaceHolder where I append the dynamically created controls:

<asp:placeholder id="placeHolder1" runat="server">
asp:placeholder>

Please see picture below:



How to Visible Field of GridView in C#

While I develop application using ASP.Net with C#, I want to share small knowledge to visible unnecessary fields in GridView. Sometime you don't want to show some data in interface, but you still can use theirs values. It just high on the form. Please see code below to visible field in gridview:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
        e.Row.Cells[1].Visible = false;
}

- e.Row.Cells[1].Visible is the field index that you want to visible.

In page design of GridView:

OnRowDataBound="GridView1_RowDataBound"

When you run code, it will not see field index No1. and you can also add other field in gridview.

How to Create Class For Encrypt and Decrypt Password In C#

If you want to Encrypt and Decrypt password when insert into table
you can use code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;

namespace EnCryptDecrypt
{
class CryptorEngine
{
public static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

public static string Decrypt(string cipherString, bool useHashing)
{
byte[] keyArray;
//byte[] toEncryptArray = Convert.FromBase64String(cipherString); Original coding

byte[] toEncryptArray = Convert.FromBase64String(cipherString);

System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

tdes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
}
}

How to call in c#?

string textpassword = txtPassword.Text.Trim();
string cipherText = EnCryptDecrypt.CryptorEngine.Encrypt(textpassword, true);
value of password is cipherText

If it have error please copy code below into Web.config in the





How to Show Data In TreeView

It you have some data in table and want to show it in TreeView
You can write code below:
1. tbl_Data have have data below:
2. Then please write code below:
TreeView1.Nodes.Clear();
private void showtreeview()
SqlCommand cmd= new SqlCommand ();
cmd.Connection =conn;
cmd.CommandType=CommandType.Text;
cmd.CommandText = "Select * from tbl_data order by Leve";
SqlDataReader sqlDR = cmd.ExecuteReader();

TreeView1.Nodes.Clear();

int lvCode = 0;

while (sqlDR.Read())
{
TreeNode tn = new TreeNode();
tn.Text = sqlDR["Level"].ToString() + "-" + sqlDR["Text"].ToString();
tn.Value = sqlDR["Level"].ToString();

if (sqlDR["Level"].ToString().Equals("1")){

TreeView1.Nodes.Add(tn);
TreeView1.Nodes[TreeView1.Nodes.Count - 1].Select();

}else
{
if ( lvCode 0)
{
TreeView1.SelectedNode.ChildNodes "+
" [TreeView1.SelectedNode.ChildNodes.Count-1].Select();
}
}
else if (lvCode > int.Parse(sqlDR["Level"].ToString()))
{
TreeView1.SelectedNode.Parent.Select();
}


TreeView1.SelectedNode.ChildNodes.Add(tn);
}
lvCode = int.Parse(sqlDR["Level"].ToString());


}
}

3. When already to finish your code you can run it.

How to Compare Date Time In C#

This article for know about during of start date and end date.
Example: StartDate= 10/05/2009 and EndDate= 15/05/2009
You want to know about during of 2 date. how do you do?
and you want to know which first and which last.
If you want to do it please see code below:

1. Find during of this date.

DateTime startDate= new DateTime();
DateTime endDate=new DateTime();

startDate=Convert.ToDateTime(txtStartDate.Text);
endDate=Convert.ToDateTime(txtEndDate.Text);

int during= endDate-startDate;

Response.Write(during.ToString());

But this code for find during that in the same month and the same year.
can not calculate in different year and month. But we can compare date time
by using function of C#.

2. Compare Date Time

DateTime startDate= new DateTime();
DateTime endDate=new DateTime();

startDate=Convert.ToDateTime(txtStartDate.Text);
endDate=Convert.ToDateTime(txtEndDate.Text);

int during =endDate.CompareTo(startDate);

if (startDate > endDate)
{
Response.Write("Start Date is big");
}
else
{
Response.Write("Start Date is Small");
}

How to Show Value From Select Multi Record In SQL

This code for show each values that you select many record
from sql server.

please see code below:

string str="select Name form tblName where ID between 1 and 5";
Sqlcommand cmd=new Sqlcommand(str,connection);
DataReader Dreader=cmd.ExecuteReader();

While (Dreader.Read())
{
if (DReader["ID"].ToString().Equals("1")) txtName1.Text = DReader["Name"].ToString();
if (DReader["ID"].ToString().Equals("2")) txtName2.Text = DReader["Name"].ToString();
if (DReader["ID"].ToString().Equals("3")) txtName3.Text = DReader["Name"].ToString();
if (DReader["ID"].ToString().Equals("4")) txtName4.Text = DReader["Name"].ToString();
if (DReader["ID"].ToString().Equals("5")) txtName5.Text = DReader["Name"].ToString();

}
Dreader.Close();

How to Show Header of GridView when Empty Data in C#

In using gridview it always show data when in table have data.
if in table not have data when you use it, not show anything in
gridview. but we can show header by nothing data in table.
If you want to know and want to use it please see code and
practice it as below:

/// Show grid even if datasource is empty

protected void EmptyGridFix(GridView grdView)
{
// normally executes after a grid load method

if (grdView.Rows.Count == 0 &&
grdView.DataSource != null)
{
DataTable dt = null;

// need to clone sources otherwise it will be indirectly adding to

// the original source


if (grdView.DataSource is DataSet)
{
dt = ((DataSet)grdView.DataSource).Tables[0].Clone();
}
else if (grdView.DataSource is DataTable)
{
dt = ((DataTable)grdView.DataSource).Clone();
}

if (dt == null)
{
return;
}

dt.Rows.Add(dt.NewRow()); // add empty row

grdView.DataSource = dt;
grdView.DataBind();

// hide row

grdView.Rows[0].Visible = false;
grdView.Rows[0].Controls.Clear();
}

// normally executes at all postbacks

if (grdView.Rows.Count == 1 &&
grdView.DataSource == null)
{
bool bIsGridEmpty = true;

// check first row that all cells empty

for (int i = 0; i < grdView.Rows[0].Cells.Count; i++)
{
if (grdView.Rows[0].Cells[i].Text != string.Empty)
{
bIsGridEmpty = false;
}
}
// hide row

if (bIsGridEmpty)
{
grdView.Rows[0].Visible = false;
grdView.Rows[0].Controls.Clear();
}
}
}


/// This code below for select data form table. write it in page load in page

protected void LoadGrid()
{
DataSet dsMyDataSet = new Dataset();
SqlDataAdapter Dadapter=new SqlDataAdapter _
("Select * From TableName",Connection);
Dadapter.Fill(dsMyDataSet);


// obtain dataset/datatable from DAL/BAL


grdYourGrid.DataSource = dsMyDataSet.Table[0];
grdYourGrid.DataBind();

this.EmptyGridFix(grdYourGrid);
}

Using JavaScript To Select GridView Rows

This article is code for select rows in GridView by using JavaScript and C# language. It is every important by when you select on this row it is show all data in cell in Grid View to Textbox. add when select on each row it always show highlights on row that you select.

1. You must have one table that have data

ID

Name

Sex

001

Theary

F

002

Dara

M

003

Bunney

F

004

Kakda

M

005

Sokhut

M

2. Open Visual Basic and Create New Project and write code below:

a. In .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SystemCodingScheme.aspx.cs" Inherits="PerfexBankSystem.SystemCodingScheme" EnableEventValidation="false" %>

Make sure you have this code “EnableEventValidation="false"” in this tage in your page.

you must have JavaScript Code for Hightlights on row in Grid View

3. In aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
public partial class grid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
//-------------------For call Function of JavaScript for show hightlights on row-----------------------
    protected void GridView1_RowDataBound(object sender, 
                    GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "javascript:setMouseOverColor(this);";
            e.Row.Attributes["onmouseout"] = "javascript:setMouseOutColor(this);";
            e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink (this.GridView1, "Select$" + e.Row.RowIndex);
        }
    }
//-------------------/For call Function of JavaScript for show hightlights on row-----------------------
 
// --------------------Event when you select on each row in Grid View------------------
 
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
       //-----------For recieve data from cell in gridview in textbox------------
        TextBox1.Text = GridView1.SelectedRow.Cells[0].Text;
        TextBox2.Text = GridView1.SelectedRow.Cells[1].Text;
        TextBox3.Text = GridView1.SelectedRow.Cells[2.Text;
    }
// --------------------/Event when you select on each row in Grid View------------------
 
}

4. Show Result below

ID

Name

Sex

001

Theary

F

002

Dara

M

003

Bunney

F

004

Kakda

M

005

Sokhut

M