string[] n = { "a", "b","c" };
foreach (string c in n)
{
string k = c;
}
for (int i = 0; i < n.Length; ++i)
{
string b = n[i];
}
Sunday, November 29, 2009
Thursday, November 26, 2009
To Store and Retrieval Image in Windows Application
****************************************************************
Upload the Image in SqlServer2005
SqlConnection con = new SqlConnection("server=vivek\\server2005;initial catalog=TESTIMAGE;integrated security=true");
con.Open();
SqlCommand cmd = new SqlCommand("IMG_INSERT", con);
cmd.Parameters.AddWithValue("@id", textBox2.Text);
//////////////////////
MemoryStream stream = new MemoryStream();
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
cmd.Parameters.AddWithValue("@img", pic);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
MessageBox.Show("Sucessfully Saved");
*************************************************************************
Download and Display in to Picture using Timer
//Global Declaration
private string s = ConfigurationSettings.AppSettings["conn"];
DataSet ds = new DataSet();
static int cnt = 0;
//Form Load Coding
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(s);
con.Open();
SqlDataAdapter ada = new SqlDataAdapter("SELECT studid,PHOTO FROM studentregistration", con);
ada.Fill(ds);
}
//Timer Coding
private void timer1_Tick(object sender, EventArgs e)
{
Bitmap map ;
if (cnt < ds.Tables[0].Rows.Count)
{
byte[] bytes = (byte[])ds.Tables[0].Rows[cnt][1];
MemoryStream mem = new MemoryStream(bytes);
map = new Bitmap(mem);
pictureBox1.Image = map;
cnt += 1;
}
else
{
cnt = 0;
}
}
Upload the Image in SqlServer2005
SqlConnection con = new SqlConnection("server=vivek\\server2005;initial catalog=TESTIMAGE;integrated security=true");
con.Open();
SqlCommand cmd = new SqlCommand("IMG_INSERT", con);
cmd.Parameters.AddWithValue("@id", textBox2.Text);
//////////////////////
MemoryStream stream = new MemoryStream();
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
cmd.Parameters.AddWithValue("@img", pic);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
MessageBox.Show("Sucessfully Saved");
*************************************************************************
Download and Display in to Picture using Timer
//Global Declaration
private string s = ConfigurationSettings.AppSettings["conn"];
DataSet ds = new DataSet();
static int cnt = 0;
//Form Load Coding
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(s);
con.Open();
SqlDataAdapter ada = new SqlDataAdapter("SELECT studid,PHOTO FROM studentregistration", con);
ada.Fill(ds);
}
//Timer Coding
private void timer1_Tick(object sender, EventArgs e)
{
Bitmap map ;
if (cnt < ds.Tables[0].Rows.Count)
{
byte[] bytes = (byte[])ds.Tables[0].Rows[cnt][1];
MemoryStream mem = new MemoryStream(bytes);
map = new Bitmap(mem);
pictureBox1.Image = map;
cnt += 1;
}
else
{
cnt = 0;
}
}
Monday, November 23, 2009
To add controls dynamically in Web Application
Steps:
i)To add ContentHolder control in Webpage
ii) Create an object for Label
Label l = new Label();
l.Text="Hai"
iii) PlaceHolder1.Controls.Add(l);
i)To add ContentHolder control in Webpage
ii) Create an object for Label
Label l = new Label();
l.Text="Hai"
iii) PlaceHolder1.Controls.Add(l);
To Load All Country Names in DropDownList
private void PopulateCountryName(DropDownList dropDown)
{
Dictionary<string, string> objDic = new Dictionary<string, string>();
foreach (CultureInfo ObjCultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
RegionInfo objRegionInfo = new RegionInfo(ObjCultureInfo.Name);
if (!objDic.ContainsKey(objRegionInfo.EnglishName))
{
objDic.Add(objRegionInfo.EnglishName, objRegionInfo.TwoLetterISORegionName.ToLower());
}
}
List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(objDic);
myList.Sort(
delegate(KeyValuePair<string, string> firstPair,
KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
foreach (KeyValuePair<string, string> val in myList)
{
dropDown.Items.Add(new ListItem(val.Key, val.Value));
}
}
{
Dictionary<string, string> objDic = new Dictionary<string, string>();
foreach (CultureInfo ObjCultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
RegionInfo objRegionInfo = new RegionInfo(ObjCultureInfo.Name);
if (!objDic.ContainsKey(objRegionInfo.EnglishName))
{
objDic.Add(objRegionInfo.EnglishName, objRegionInfo.TwoLetterISORegionName.ToLower());
}
}
List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(objDic);
myList.Sort(
delegate(KeyValuePair<string, string> firstPair,
KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
foreach (KeyValuePair<string, string> val in myList)
{
dropDown.Items.Add(new ListItem(val.Key, val.Value));
}
}
Friday, November 20, 2009
SQL Queries
*****************************************************************
To Set column values as empty which contains zeros
SELECT (case when quantity = 0 then '' else quantity end) AS 'quantity'
FROM stock
To Set column values as empty which contains zeros
SELECT (case when quantity = 0 then '' else quantity end) AS 'quantity'
FROM stock
Tuesday, November 17, 2009
Abstract Class And Interface
Main Program:
namespace abstractandinterface
{
class Program
{
static void Main(string[] args)
{
////////////////////////////////////////////abstract class inheritance
abstractclass inheritabstract;
inheritabstract = new inheritabstractclass();
string rd = Convert.ToString(Console.ReadLine());
Console.WriteLine("\n");
inheritabstract.Custid = rd;
rd = inheritabstract.commondetails();
Console.WriteLine("Abstract Output\n");
Console.WriteLine(rd);
Console.WriteLine("\n");
Console.Read();
///////////////////////////////////////interface implementation
interfaceclass inheritinterface;
implementinheritance implement = new implementinheritance();
inheritinterface = (interfaceclass)implement;
string rd1 = Convert.ToString(Console.ReadLine());
Console.WriteLine("\n");
implement.custname = rd1;
Console.WriteLine("Interface Ouptput\n");
Console.WriteLine(rd1);
Console.WriteLine("\n");
Console.Read();
}
}
}
Abstract Class:
namespace abstractandinterface
{
abstract class abstractclass
{
string custid;
public string Custid
{
get { return custid; }
set { custid = value; }
}
static string custname;
public static string Custname
{
get { return abstractclass.custname; }
set { abstractclass.custname = value; }
}
public string commondetails( )
{
return custid;
}
public abstract string account();
}
}
Interface Class
namespace abstractandinterface
{
interface interfaceclass
{
string account();
}
}
Inherit Abstract Class
namespace abstractandinterface
{
class inheritabstractclass:abstractclass
{
public override string account()
{
return "";
}
}
}
Implement Interface
namespace abstractandinterface
{
class implementinheritance:interfaceclass
{
static string custid;
public static string Custid
{
get { return implementinheritance.custid; }
set { implementinheritance.custid = value; }
}
public string custname;
private string Custname
{
get { return custname; }
set { custname = value; }
}
private string custaddress;
public string Custaddress
{
get { return custaddress; }
set { custaddress = value; }
}
#region interfaceclass Members
public string account()
{
return custid;
}
#endregion
}
}
namespace abstractandinterface
{
class Program
{
static void Main(string[] args)
{
////////////////////////////////////////////abstract class inheritance
abstractclass inheritabstract;
inheritabstract = new inheritabstractclass();
string rd = Convert.ToString(Console.ReadLine());
Console.WriteLine("\n");
inheritabstract.Custid = rd;
rd = inheritabstract.commondetails();
Console.WriteLine("Abstract Output\n");
Console.WriteLine(rd);
Console.WriteLine("\n");
Console.Read();
///////////////////////////////////////interface implementation
interfaceclass inheritinterface;
implementinheritance implement = new implementinheritance();
inheritinterface = (interfaceclass)implement;
string rd1 = Convert.ToString(Console.ReadLine());
Console.WriteLine("\n");
implement.custname = rd1;
Console.WriteLine("Interface Ouptput\n");
Console.WriteLine(rd1);
Console.WriteLine("\n");
Console.Read();
}
}
}
Abstract Class:
namespace abstractandinterface
{
abstract class abstractclass
{
string custid;
public string Custid
{
get { return custid; }
set { custid = value; }
}
static string custname;
public static string Custname
{
get { return abstractclass.custname; }
set { abstractclass.custname = value; }
}
public string commondetails( )
{
return custid;
}
public abstract string account();
}
}
Interface Class
namespace abstractandinterface
{
interface interfaceclass
{
string account();
}
}
Inherit Abstract Class
namespace abstractandinterface
{
class inheritabstractclass:abstractclass
{
public override string account()
{
return "";
}
}
}
Implement Interface
namespace abstractandinterface
{
class implementinheritance:interfaceclass
{
static string custid;
public static string Custid
{
get { return implementinheritance.custid; }
set { implementinheritance.custid = value; }
}
public string custname;
private string Custname
{
get { return custname; }
set { custname = value; }
}
private string custaddress;
public string Custaddress
{
get { return custaddress; }
set { custaddress = value; }
}
#region interfaceclass Members
public string account()
{
return custid;
}
#endregion
}
}
Thursday, November 12, 2009
javascript for validation
{
if(57<48) returnvalue="false;" keycode="=" returnvalue =" true;"><97)><65) returnvalue =" false;" keycode="=" keycode="=" keycode="=" returnvalue =" true;" keycode ="=" returnvalue =" false;" emailpat="/^(.+)@(.+)$/" specialchars="">@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
var matchArray=emailStr.match(emailPat)
if (matchArray==null)
{
alert("Your Email Address must be valid!")
return false
}
var user=matchArray[1]
var domain=matchArray[2]
if (user.match(userPat)==null)
{
alert("Your Email Address must be valid!")
return false;
}
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null)
{
for (var i=1;i<=4;i++) { if (IPArray[i]>255)
{
alert("Your Email Address must be valid!")
return false
}
}
return true
}
var domainArray=domain.match(domainPat)
if (domainArray==null)
{
alert("Your Email Address must be valid!")
return false
}
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2>3)
{
alert("The Email Address must end in a three-letter domain, or two letter country.")
return false
}
if (len<2) regexp =" /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=" retvalue =" inputString;" ch =" retValue.substring(0," ch ="=" retvalue =" retValue.substring(1," ch =" retValue.substring(0," ch =" retValue.substring(retValue.length-1," ch ="=" retvalue =" retValue.substring(0," ch =" retValue.substring(retValue.length-1," retvalue =" retValue.substring(0," ndecimal =" 0;" xtxt="textValue.value;" xtxt =" document.getElementById(" txtlen=" xTxt.length;" i =" 0;" x =" xTxt.substr(i," x ="=" ndecimal =" nDecimal"> 1)
{
alert("You have entered more than one decimal point!\nPlease only enter one!");
textValue.value="";
textValue.focus();
return false;
}
}
}
function IgnoreDecimal(textValue)
{
var nDecimal = 0;
var i;
var x;
var xTxt=textValue.value;
//var xTxt = document.getElementById("ctl00_ContentPlaceHolder1_txtBasicDuty").value;
var txtLen= xTxt.length;
for(i = 0; i < x =" xTxt.substr(i," x ="=" ndecimal =" nDecimal"> 0)
{
alert("You have entered decimal point!\nPlease ignore decimal point!");
textValue.value="";
textValue.focus();
return false;
}
}
}
CreditCard validation
---------------------------
public bool IsCreditCardValid(string cardNumber)
{
const string allowed = "0123456789";
int i;
StringBuilder cleanNumber = new StringBuilder();
for (i = 0; i <>= 0)
cleanNumber.Append(cardNumber.Substring(i, 1));
}
if (cleanNumber.Length <> 16)
return false;
for (i = cleanNumber.Length + 1; i <= 16; i++) cleanNumber.Insert(0, "0"); int multiplier, digit, sum, total = 0; string number = cleanNumber.ToString(); for (i = 1; i <= 16; i++) { multiplier = 1 + (i % 2); digit = int.Parse(number.Substring(i - 1, 1)); sum = digit * multiplier; if (sum > 9)
sum -= 9;
total += sum;
}
return (total % 10 == 0);
}
--------------public static bool IsDate(string strdt)
{
try
{
if (strdt.Trim() != "")
{
DateTime dt = Convert.ToDateTime(strdt);
}
return true;
}
catch
{
return false;
}
}
public static bool IsNumeric(string numberString)
{
try
{
if (numberString.Trim() != "")
{
double num = Convert.ToDouble(numberString);
}
return true;
}
catch
{
return false;
}
}
openFileDialog c#
string Fname, Fext,fpath ;
int Fsize;
private void GetOpenFileDialog()
{
openFileDialogX.CheckPathExists = true;
openFileDialogX.Filter = "Image Files (*.bmp;*.jpg;*.jpeg)|*.bmp;*.jpg;*.jpeg|" + "PNG files (*.png)|*.png|text files (*.text)|*.txt|doc files (*.doc)|*.doc|pdf files (*.pdf)|*.pdf|excel files(*.xls)|*.xls|excel files07(*.xlsx)|*.xlsx";
openFileDialogX.Multiselect = false;
openFileDialogX.AddExtension = true;
openFileDialogX.ValidateNames = true;
openFileDialogX.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
openFileDialogX.ShowDialog();
fpath = openFileDialogX.FileName.ToString();
fname=System.IO.Path.GetFileName(openFileDialogX.FileName).ToUpper();
Fsize = openFileDialogX.FileName.Length;
Fext = System.IO.Path.GetExtension(Fname);
}
Fill gridview using Datareader and Dataset
Fill gridview using Datareader:
SqlConnection con = new SqlConnection("server=.;database=northwind;integrated security=true");
SqlCommand com = new SqlCommand("select * from Categories", con);
SqlDataReader DR;
con.Open();
DR = com.ExecuteReader(CommandBehavior.CloseConnection);
DR.Read();
GridView1.DataSource = DR;
GridView1.DataBind();
Fill gridview using Datareader:
SqlConnection con = new SqlConnection("server=.;database=northwind;integrated security=true");
SqlDataAdapter DA = new SqlDataAdapter("select * from Categories", con);
DataSet DS = new DataSet();
DA.Fill(DS);
GridView1.DataSource = DS;
GridView1.DataBind();
Dynamic Datatable in C#
Create DataTable Dynamically using C#
DataTable DT = new DataTable();
//Create Column
DT.Columns.Add("Column 1");
DT.Columns.Add("Column 2");
DT.Columns.Add("Column 3");
//End Column
//Create and Add New Row
DataRow DTRow= DT.NewRow();
//Inserting values to each cell in a row
DTRow[0] = "First cell";
DTRow[1] = "Second cell";
DTRow[2] = "Third cell";
DT.Rows.Add(DTRow);
DataTable DT = new DataTable();
//Create Column
DT.Columns.Add("Column 1");
DT.Columns.Add("Column 2");
DT.Columns.Add("Column 3");
//End Column
//Create and Add New Row
DataRow DTRow= DT.NewRow();
//Inserting values to each cell in a row
DTRow[0] = "First cell";
DTRow[1] = "Second cell";
DTRow[2] = "Third cell";
DT.Rows.Add(DTRow);
retrieve file from database c#
{
string fileId = "10";
connection.Open();
SqlCommand command = new SqlCommand("SELECT flname,flcontent FROM upload WHERE fid = @FileId", connection);
command.Parameters.AddWithValue("@FileId", fileId);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
reader.Read();
byte[] content = reader["flcontent"] as byte[];
string filename = reader["flname"].ToString();
Response.Clear();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.AddHeader("Content-Length", content.Length.ToString());
Response.OutputStream.Write(content, 0, content.Length);
Response.End();
//writeByteArrayToFile(content, filename);
}
}
fill treeview programmatically in asp.net
{
foreach (DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode();
tn.Text = dr["name"].ToString();
//tn.Value = dr["idd"].ToString();
nodes.Add(tn);
//If node has child nodes, then enable on-demand populating
//tn.PopulateOnDemand = ((int)dr["childnodecount"] > 0);
}
}
public void TreeViewPopulateSubLevel(String parentid, TreeNode parentNode)
{
DB.DbConnect(con);
cmd = new SqlCommand("select IDD,NAM,(select count(*) FROM model WHERE parentid=sc.idd) childnodecount FROM model sc where parentid='" + parentid + "' ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
TreeViewPopulateNodes(dt, parentNode.ChildNodes);
}
public void TreeViewPopulateRootLevel(string Fld, TreeView TreeView1)
{
cmd = new SqlCommand("select IDD,NAM,(select count(*) FROM model WHERE parentid=sc.IDD) childnodecount FROM model sc where parentid IS NULL and nam='" + Fld + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
TreeViewPopulateNodes(dt, TreeView1.Nodes);
}
reset controls in asp.net
------
public void ResetFormControlValues(this) 'or'
public void ResetFormControlValues(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ResetFormControlValues(c);
}
else
{
switch (c.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.CheckBox":
((CheckBox)c).Checked = false;
break;
case "System.Web.UI.WebControls.RadioButton":
((RadioButton)c).Checked = false;
break;
}
}
}
------------------------------------------------------
VB.Net
----------
Public Sub ResetFormControlValues(ByVal parent As Control)
'Dim c As New Control
For Each c As Control In parent.Controls
If c.Controls.Count > 0 Then
ResetFormControlValues(c)
Else
Select Case (c.GetType().ToString())
Case "System.Web.UI.WebControls.TextBox"
CType(c, TextBox).Text = ""
Case "System.Web.UI.WebControls.CheckBox"
CType(c, CheckBox).Checked = False
Case "System.Web.UI.WebControls.RadioButton"
CType(c, RadioButton).Checked = False
Case "System.Web.UI.WebControls.DropDownList"
CType(c, DropDownList).SelectedIndex = 0
End Select
End If
Next
End Sub
Restrict file selected in FileUpload control in Asp.Net
private bool IsValidFile(string filePath)
{
bool isValid = false;
string[] fileExtensions = { ".bmp", ".jpg", ".png", ".gif", ".jpeg", ".doc", ".docx", ".txt", ".rtf", ".RTF", ".DOC", ".DOCX", ".TXT", ".BMP", ".JPG", ".PNG", ".JPEG" };
for (int i = 0; i < fileExtensions.Length; i++)
{
if (filePath.Contains(fileExtensions[i]))
{
isValid = true;
}
}
return isValid;
}
{
bool isValid = false;
string[] fileExtensions = { ".bmp", ".jpg", ".png", ".gif", ".jpeg", ".doc", ".docx", ".txt", ".rtf", ".RTF", ".DOC", ".DOCX", ".TXT", ".BMP", ".JPG", ".PNG", ".JPEG" };
for (int i = 0; i < fileExtensions.Length; i++)
{
if (filePath.Contains(fileExtensions[i]))
{
isValid = true;
}
}
return isValid;
}
split, substring and remove null values in string array in c#
{
Sltstr = SplitStr.Split((SplitbyStr).ToCharArray());
return Sltstr;
}
public string MySubString(string Mystr, int cnt)
{
MyInt = Mystr.Length;
if (cnt > MyInt)
{
MyTemp = Mystr.Substring(0, MyInt);
}
else
{
MyTemp = Mystr.Substring(0, cnt);
}
return MyTemp;
}
public string[] RemoveEmptyFromArray(string[] OriginalArray)
{
SB.Remove(0, SB.Length);
//IEnumerator IEnu = MySplit(OriginalArray[0],":") .GetEnumerator();
//while (IEnu.MoveNext())
//{
// if (IEnu.Current.ToString() != "")
// {
// sTmp.Append(IEnu.Current.ToString()+ "||");
// }
//}
for (int i = 0; i < OriginalArray.Length; i++)
{
string s = Convert.ToString(OriginalArray[i]);
//if (i == 0 && s != "")
// if (s == "")
if (i == 0 && s != null)
{
SB.Append(Convert.ToString(s));
}
else if (Convert.ToString(SB) == "" && s != null)
{
SB.Append(Convert.ToString(s));
}
else if (s != null)
{
SB.Append("|" + Convert.ToString(s));
}
//if (Convert.ToString(OriginalArray[i]) != "")
//{
// if (i == OriginalArray.Length - 1)
// {
// SB.Append(Convert.ToString(OriginalArray[i]));
// }
// else
// {
// SB.Append(Convert.ToString(OriginalArray[i]) + "|");
// }
//}
}
return MySplit(SB.ToString(), "|");
}
fill ListBox ,CheckBoxList programetically
{
ck.Items.Clear();
for (int i = 0; i < MyDT.Rows.Count; i++)
{
ck.Items.Add(MyDT.Rows[i][0].ToString());
}
return ck;
}
public ListBox MyListBox (ListBox LB, DataTable MyDT)
{
LB.Items.Clear();
for (int i = 0; i < MyDT.Rows.Count-2; i++)
{
LB.Items.Add(MyDT.Rows[i][0].ToString());
}
return LB;
}
create table programmatically with 'n' number of column c#
public int CreateTable(string tabname1,string tabname2,string[] MyAtt)
{
try
{
MyAtt = tabname1;
MyProd = tabname2;
SB.Append("CREATE TABLE " + MyProd + " (");
SBB.Append("CREATE TABLE " + MyProd + "_QUERYLOG (");
for (int i = 0; i < MyAtt.Length; i++)
{
if (i == MyAtt.Length-1)
{
SB.Append(MyAtt[i] + " BIT,");
SBB.Append(MyAtt[i] + " BIT)");
}
else
{
SB.Append(MyAtt[i] + " BIT,");
SBB.Append(MyAtt[i] + " BIT,");
}
}
SB.Append("DESCRIPTION VARCHAR(500),NOTEPAD IMAGE,MAXIVISI INT,FILNAM VARCHAR(500))");
int I = DAL.CreateTab(SBB.ToString());
int y = DAL.CreateTab(SB.ToString());
return y;
}
catch
{
return 0;
}
}
validate programmatically VB.Net
Dim Str, j As String
Dim i As Integer
Str = T.Text
Fn_Check_Characters = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 65 And Asc(j) <= 90) Or (Asc(j) >= 97 And Asc(j) <= 122) Or (Asc(j) = 32) Or (Asc(j) = 46)) Then
Fn_Check_Characters = False
Exit For
End If
Next
End Function
Public Function Fn_Check_DataGrid_String(ByVal NewStr As String) As Boolean
Dim Str, j As String
Dim i As Integer
Fn_Check_DataGrid_String = True
For i = 1 To Len(NewStr)
j = Mid(NewStr, i, 1)
If Not ((Asc(j) >= 65 And Asc(j) <= 90) Or (Asc(j) >= 97 And Asc(j) <= 122) Or (Asc(j) = 32) Or (Asc(j) = 46)) Then
Fn_Check_DataGrid_String = False
Exit For
End If
Next
End Function
Public Function Fn_Check_Extra_Characters(ByVal T As TextBox) As Boolean
Dim Str, j As String
Dim i As Integer
Str = T.Text
Fn_Check_Extra_Characters = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 65 And Asc(j) <= 90) Or (Asc(j) >= 97 And Asc(j) <= 122) Or (Asc(j) = 32) Or (Asc(j) = 46) Or (Asc(j) = 44) Or (Asc(j) = 47) Or (Asc(j) = 40) Or (Asc(j) = 41) Or (Asc(j) = 59)) Then
Fn_Check_Extra_Characters = False
Exit For
End If
Next
End Function
Public Function Fn_Check_Pure_Numbers(ByVal T As TextBox) As Boolean
Dim Str, j As String
Dim i As Integer
Str = T.Text
Fn_Check_Pure_Numbers = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 48 And Asc(j) <= 57)) Then
Fn_Check_Pure_Numbers = False
Exit For
End If
Next
End Function
Public Function Fn_Check_Pure_Numbers1(ByVal T As String) As Boolean
Dim Str, j As String
Dim i As Integer
Str = T
Fn_Check_Pure_Numbers1 = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 48 And Asc(j) <= 57)) Then
Fn_Check_Pure_Numbers1 = False
Exit For
End If
Next
End Function
Public Function Fn_Check_DataGrid_Numbers(ByVal NewStr As String) As Boolean
Dim j As String
Dim i As Integer
Fn_Check_DataGrid_Numbers = True
For i = 1 To Len(NewStr)
j = Mid(NewStr, i, 1)
If Not ((Asc(j) >= 48 And Asc(j) <= 57)) Then
Fn_Check_DataGrid_Numbers = False
Exit For
End If
Next
End Function
Public Function Fn_Check_Numbers(ByVal T As TextBox) As Boolean
Dim Str, j As String
Dim i, Cnt As Integer
Cnt = 0
Str = Trim(T.Text)
Fn_Check_Numbers = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If j = "." Then
Cnt = Cnt + 1
If Cnt = 2 Then
Fn_Check_Numbers = False
Exit For
End If
End If
If Not ((Asc(j) >= 48 And Asc(j) <= 57) Or Asc(j) = 46 Or Asc(j) = 45) Then
Fn_Check_Numbers = False
Exit For
End If
Next
End Function
Public Function Fn_Check_Alpha_Numeric(ByVal T As TextBox) As Boolean
Dim Str, j As String
Dim i As Integer
Str = T.Text
Fn_Check_Alpha_Numeric = True
For i = 1 To Len(Str)
j = Mid(Str, i, 1)
If Not ((Asc(j) >= 65 And Asc(j) <= 90) Or (Asc(j) >= 97 And Asc(j) <= 122) Or (Asc(j) = 32) Or (Asc(j) >= 48 And Asc(j) <= 57) Or (Asc(j) = 46)) Then
Fn_Check_Alpha_Numeric = False
Exit For
End If
Next
End Function
Public Function Fn_Date_Validations(ByVal EDay As DropDownList, ByVal Emonth As DropDownList, ByVal EYear As DropDownList) As Boolean
Dim Str As String
Fn_Date_Validations = True
If Emonth.SelectedItem.Text = "Feb" Then
If (Val(EYear.SelectedItem.Text) Mod 4) = 0 Then
If Val(EDay.SelectedItem.Text) > 29 Then
Fn_Date_Validations = False
Exit Function
End If
Else
If Val(EDay.SelectedItem.Text) > 28 Then
Fn_Date_Validations = False
Exit Function
End If
End If
Else
Str = Emonth.SelectedItem.Text
If Not (Str = "Jan" Or Str = "Mar" Or Str = "May" Or Str = "Jul" Or Str = "Aug" Or Str = "Oct" Or Str = "Dec") Then
If Val(EDay.SelectedItem.Text) > 30 Then
Fn_Date_Validations = False
Exit Function
End If
End If
End If
End Function
Public Sub Pr_Month_Numeric_Validations(ByVal EDay As DropDownList, ByVal Emonth As DropDownList, ByVal EYear As DropDownList)
Dim Str As String
If EYear.SelectedItem.Text = "Year" Or Emonth.SelectedItem.Text = "Month" Then
Exit Sub
End If
If Emonth.SelectedItem.Text = "2" Then
If (EYear.SelectedItem.Text Mod 4) = 0 Then
Call Pr_Fill_Combo_Days(EDay, 29)
Else
Call Pr_Fill_Combo_Days(EDay, 28)
End If
Else
Str = Emonth.SelectedItem.Text
If Str = "1" Or Str = "3" Or Str = "5" Or Str = "7" Or Str = "8" Or Str = "10" Or Str = "12" Then
Call Pr_Fill_Combo_Days(EDay, 31)
Else
Call Pr_Fill_Combo_Days(EDay, 30)
End If
End If
End Sub
Public Function removesplcharacter(ByVal ValArray() As Char) As String
Dim usability As String = ""
For i As Integer = 0 To ValArray.Length - 1
If Not ValArray(i) = " " And Not ValArray(i) = "-" And Not ValArray(i) = "." Then
usability = usability + ValArray(i)
End If
Next
Return usability
End Function
covert number into words(like denomination)
Dim NoArr() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0}
Dim StrLength, i As Integer
Dim TNo As String
TNo = Trim(Str(NumVal))
StrLength = Len(TNo)
For i = 0 To StrLength - 1
NoArr(i) = Microsoft.VisualBasic.Right(TNo, 1)
TNo = Microsoft.VisualBasic.Left(TNo, StrLength - (i + 1))
Next i
Fn_NumToWord = ConvStr(NoArr)
End Function
Private Function ConvStr(ByVal NoA As Integer()) As String
Dim CrVal, LakVal, ThVal, Hval, LaVal As Integer
Dim CoStr As String
CrVal = (NoA(8) * 10) + NoA(7)
LakVal = (NoA(6) * 10) + NoA(5)
ThVal = (NoA(4) * 10) + NoA(3)
Hval = NoA(2)
LaVal = (NoA(1) * 10) + NoA(0)
CoStr = IndStr(CrVal, 0) & IndStr(LakVal, 1) & IndStr(ThVal, 2) & IndStr(Hval, 3)
Dim LaStr As String = IndStr(LaVal, 4)
If CoStr <> "" And LaStr <> "" Then
ConvStr = CoStr & " and " & LaStr
Else
ConvStr = CoStr & LaStr
End If
End Function
Private Function IndStr(ByVal NoVal As Integer, ByVal OrdNo As Integer) As String
Dim S, K As String
Dim LastStr() As String = {"", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Tweleve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen ", "Twenty"}
Dim OrdArr() As String = {"Crore ", "Lakh ", "Thousand ", "Hundred ", ""}
Dim Valstr() As String = {"", "", "Twenty ", "Thirty ", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}
If NoVal < 20 Then
S = LastStr(NoVal)
Else
S = Valstr(Int(NoVal / 10)) & LastStr(NoVal Mod 10)
End If
If S <> "" Then IndStr = S & OrdArr(OrdNo)
End Function
date coversion(American to Indian Format and vice versa)
Try
Dim strr(), str As String
str = dates
strr = dates.Split("/")
str = strr(0)
strr(0) = strr(1)
strr(1) = str
dates = ""
dates = strr(0) & "/"
dates += strr(1) & "/"
dates += strr(2)
Return dates
Catch ex As Exception
End Try
End Function
Export DataSet To Excel VB.Net
Public Sub ExportDataSetToExcel(ByVal dt As DataTable, ByVal filename As String)
Dim response As HttpResponse = HttpContext.Current.Response
' first let's clean up the response.object
response.Clear()
response.Charset = ""
' set the response mime type for excel
response.ContentType = "application/vnd.ms-excel"
response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & """")
' create a string writer
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
' instantiate a datagrid
Dim dg As New GridView()
dg.AllowPaging = False
dg.DataSource = dt
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
response.[End]()
End Using
End Using
End Sub
Dim response As HttpResponse = HttpContext.Current.Response
' first let's clean up the response.object
response.Clear()
response.Charset = ""
' set the response mime type for excel
response.ContentType = "application/vnd.ms-excel"
response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & """")
' create a string writer
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
' instantiate a datagrid
Dim dg As New GridView()
dg.AllowPaging = False
dg.DataSource = dt
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
response.[End]()
End Using
End Using
End Sub
upload and retrieve images,doc,docx,txt to and from database C#
----------------------------------------
upload
--------
string fileName = System.IO.Path.GetFileName(this.FileUpload1.FileName);
byte[] fileContent = this.FileUpload1.FileBytes;
con.open();
using (SqlCommand command = new SqlCommand("insert into imgupl values(@Filename,@FileContent)", con))
{
SqlParameter fileNameParameter = new SqlParameter("@Filename", System.Data.SqlDbType.NVarChar, 255);
fileNameParameter.Value = fileName ;
SqlParameter fileContentParameter = new SqlParameter("@FileContent", System.Data.SqlDbType.Image);
fileContentParameter.Value = fileContent ;
command.Parameters.AddRange(new SqlParameter[] { fileNameParameter, fileContentParameter });
command.ExecuteNonQuery();
MyTemp = "Record Saved Successfully.";
}
----------------------------------------
download:
-------------
string fileId = "1";
using (SqlCommand command = new SqlCommand("SELECT filename ,uploadedfile FROM imgupl WHERE id = @FileId", connection))
{
command.Parameters.AddWithValue("@FileId", fileId.Replace("-", "||"));
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
reader.Read();
byte[] content = reader["uploadedfile "] as byte[];
string filename = reader["filename "].ToString();
Response.Clear();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.AddHeader("Content-Length", content.Length.ToString());
Response.OutputStream.Write(content, 0, content.Length);
Response.End();
}
}
Subscribe to:
Posts (Atom)