Showing posts with label csharp. Show all posts
Showing posts with label csharp. Show all posts

Tuesday, August 27, 2013

How to use For loop in C#.net

In this articles i will show how to use looping statement in c#.net.In this examples A program to add to textBox at run time. Here i placed one button to perform click event.
code for button click
{
int x=30;
for(int i=1;i<=10;i++)
{TextBox txt=New TextBox();
txt.Text="Txxt"+i;
txt.Location=New Point(100,x);
This.Controls.Add(txt);
x=x+30;
}
In the above code i created 10 text box using for loop condition.The for loop condition takes maximum iteration up to 10 which i was given at condition


Wednesday, August 7, 2013

How to create and consume usercontrol without vs.net

Title:How to access user control in asp.net

Description:The use controls can be used when we require a control which can be working as per our requirement.Now i would like to explain how to access this into our web application
1.Use notepad or some other editor and write all aspx/js/html code in it.Save it with .ascx extension
2.Add the created .ascx to the current project i:e copy it into current project folder
3.Go to the page where we want to consume this control and add <%@Register--%> directive
<%@Register Tagprefix="Nit" TagName="RichBanner" src="banner.ascx"%>
4.In the same page now create controls using markup
<Nit:RichBanner ID="rbl" runat="server"/>
5.To Create a control; at run time we cannot use normal syntax for use defined control.We must use load method of page to create it

Ex:-Banner a=page.Load("Banner.ascx")
similarly unload(--) to remove the controls form  form
Remember we must add it to some container after creating it
6.Every control once designed can be placed onto an assembly
7.Only ascx with a dll will be prepared and given to user(publish required)
8.<%@ control--%> directive is used instead of <%@ page--%> and contains will be placed inside a page which contains all HTML content

Tuesday, August 6, 2013

Bind data to Asp.net text box using dropdownlist in jquery

Title: JQuery set text box value in asp.net

Description:
In recent articles we known how to implement the  Data binding concept on data  controls like grid view,Data list,list etc.Here i would like to explain how to bind data to asp.net text box while leave the focus on Drop Down List using JQuery blur function.The blur function will fire when the previous controls has lost focus.

Example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Bind data to Asp.net text box using DropDownList in jquery</title>
</head>
<script type="text/javascript" src="~/jquery.min.js" ></script>
<script>
$(document).ready(function() {
$("#ddlSalesOrder").blur(function(){
var SalesOrderText = $("#ddlSalesOrder option:selected").text();
 alert(SalesOrderText);
$("#<%= txtOrderTotalAmt.ClientID %>".val(SalesOrderText); 
});
});
</script>
</head>
<body>
Amount: <asp:DropDownList ID="ddlSalesOrder" runat="server">
<asp:ListItem>100</asp:ListItem>
<asp:ListItem>125</asp:ListItem>
<asp:ListItem>150</asp:ListItem>
<asp:ListItem>175</asp:ListItem>
<asp:ListItem>200</asp:ListItem>
</asp:DropDownList>
TotalAmount:<asp:TextBox ID="txtOrderTotalAmt" runat="server"></asp:TextBox>
</body>
</html>
As you can see there is alert to confirmation for drop down selected value will come when the blur event occurs.Whenever we are using JQuery ,we should add JQuery library reference to our application.
In the above example we have taken one drop down list and text box to display the amount order .When the amount Drop down list has lost the focus ,the total Amount will be populate automatically.

Sunday, July 14, 2013

get the current month and year in asp.net

Title:How to get current month and year in asp.net using c#.net

Description:
As per previous articles we have seen how get month and year using JQuery. Now i would like to explain and give the example on the same concept in c#.net.The C#.net provide the object "Date Time" which has some properties to get the retired data.As per our discussion i will use the two methods to get the current month and year.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int year = DateTime.Now.Year;
int month = DateTime.Now.Month;
int date = (DateTime.Now.Day)+2;
Response.Write(year.ToString()+ month.ToString()+date.ToString());
}
}

Sunday, October 28, 2012

bind all font name to list box in asp.net using C#.net

In this post i will show how to Display all font name in list box  and based on the selection show the preview in label.To get the font name we have add the name space for Drawing class

Using System.Drawing.Text;
Using System.Collection;

Private void from_load(..)
{
InstalledFontCollection ifcn=new InstalledFontCollection()
IEnumerator ien;
ien=ifcn.Families.GetEnumerator();
While(ien.MoveNext()==true)
{
string si=ien.Current.Tostring();
int i=si.IndexOf("=");
si=si.Substring(i+1);
si=si.Substring(0,si.Lenght-1);
ListBox1.Items.Add(si);
}
}
//list box selected index changed event code
{
String sres=ListBox1.SelectedItem.Tostring();
Lbl.Form=new font(sres,40);
}

Wednesday, June 20, 2012

how to encrypt a file in c#

Encryption is a secure process ,which is used to transfer the data into code by appending a key .The resultant of the process is the encryption information. Here i will show how to encrypt a file in csharp.To do this process we have to add a name space "System.Security.Cryptography" .In this function i have used a key "pkey" to encrypt the data and the "outputpath" is resultant encrypted data
FileStream fs= new FileStream(Outputpath,FileMode.Create,FileAccess.Write);
DESCryptoServiceProvider DEScs = new DESCryptoServiceProvider();
DEScs.Key = ASCIIEncoding.ASCII.GetBytes(pKey);
DEScs.IV = ASCIIEncoding.ASCII.GetBytes(pKey);
ICryptoTransform desencrypt = DEScs.CreateEncryptor();
CryptoStream cstream = new CryptoStream(fs,desencrypt,CryptoStreamMode.Write);
fs.Close();
FileStream fsInput = new FileStream(Inputpath,FileMode.Open,FileAccess.Read)
byte[] ba = new byte[fsInput.Length];
fsInput.Read(ba, 0, ba.Length);
fsInput.Close();
cstream.Write(ba, 0, ba.Length);

Saturday, May 26, 2012

Get Images from folder and generate HTML anchor in asp.net

Here i will show how to get the image from folder then create a anchor link to that image and assigned to string builder "sb".."sPhysicalPath" is the path of gallery folder.The class Directory Info is used to get the all the image files from the folder
public static string BindImages(int images, bool isRedirecting)
{
string thumbNailFolderName = ConfigurationManager.AppSettings["ThumbFolder"];
string previewFolderName = ConfigurationManager.AppSettings["PreviewFolder"];
StringBuilder sb = new StringBuilder("");
string format = "<span><a href=\"{0}\" title=\"\"><img alt=\"\" src=\"{1}\" /></a></span>";string sPhysicalPath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["GalleryFolder"]);
DirectoryInfo oDir = new DirectoryInfo(sPhysicalPath);
FileInfo[] oFiles = oDir.GetFiles();
int i = 0;
foreach (FileInfo oFile in oFiles)
{
i++;
sb.AppendFormat(format, (isRedirecting ? "Gallery.aspx" : "school/gallery/" + previewFolderName + "/" + oFile.Name),
"school/gallery/" + thumbNailFolderName + "/" + oFile.Name);
if (i == images && images != 0)
break;
}
sb.Append("");
return sb.ToString();
}

Friday, May 25, 2012

BInd data to dropdownlist in gridview in asp.net

Title: How to bind data to drop down list in asp.net using c#.net

Description:
In previous posts i explained Asp.net bind data to grid view,bind data to dropdownlist,Bind drop down in MVC4.Bind grid view using LINQ. Here i will show how to binding the data to Drop down List inside of Grid View.Here the dropdownlist has place inside of grid view template Field .You can observe here i will bind data to both drop down and grid view While loading page.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Bind data to Dropdownlist in gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvSalesData" AllowSorting="True" Runat="server"
AllowPaging="true" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="SalesID">
 <ItemTemplate>
 <%#Eval("SID")  %>
 </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SalesPName">
 <ItemTemplate>
<%#Eval("SalesPersonName")  %>
</ItemTemplate>
</asp:TemplateField>
 <asp:TemplateField HeaderText="Samount">
 <ItemTemplate>
<%#Eval("Samt")  %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SalesCity">
<ItemTemplate>
<asp:DropDownList ID="ddl_city" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
 </form>
</body>
</html>
Code behind:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Dropdowningridview : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["bhaskarconnection"].Tostring());

protected void Page_Load(object sender, EventArgs e)
{
If(!page.IsPostBack)
{
//Bind data to gridview
BindOrdrGrid();
//Bind data to Dropdown in gridview
BindDropdownGrid();
}
private void BindOrdrGrid()
{
 SqlDataAdapter Ordr_ad = new SqlDataAdapter("select * from Order_details", cn);
 DataSet Ordr_ds = new DataSet();
 Ordr_adp.Fill(Ordr_ds, "Order_details");
 GvSalesData.DataSource = Ordr_ds;
 GvSalesData.DataBind(); 
}
private void BindDropdownGrid()
{
cn.Open();
SqlDataAdapter Ddl_ad = new SqlDataAdapter("select * from order_city", cn);
DataSet Ddl_ds = new DataSet();
ad.Fill(Ddl_ds, "order_city");
foreach (GridViewRow row in GvSalesData.Rows)
{
DropDownList _ddlcity = (DropDownList)(GvSalesData.Rows[row.RowIndex].Cells[4].FindControl("ddl_city"));
_ddlcity.DataSource = Ddl_ds;
_ddlcity.DataValueField = "CID";
_ddlcity.DataTextField = "City_name";
_ddlcity.DataBind();
}
}

Wednesday, May 23, 2012

How to get random number and string in c#.net

Here i will show how to get the random  text from given user input in asp.net.The method GetRandomTextKey() has taken the length as parameter.The logic"minValue + rndValue * randomRange" has used to generate a random text.Asp.net provide a class which Rnadom is used in this process
 public static string GetRandomTextKey(int length)
    {
        Random rnd = new Random((int)System.DateTime.Now.Ticks);
        System.Text.StringBuilder randomText = new
        System.Text.StringBuilder(length);

        int minValue = 65;
        int maxValue = 90;
        int randomRange = maxValue - minValue;

        double rndValue;
        for (int i = 0; i < length; i++)
        {
            rndValue = rnd.NextDouble();
            randomText.Append((char)(minValue + rndValue * randomRange));
        }

        return randomText.ToString();
    }
              

Wednesday, May 16, 2012

how to execute sql query in c sharp

Here i will show how to Excute the sql query in sql server using c#. For this I will use one method with two parameters which are database connection string and file name.Then read the text in file and passed to string array.Finally we will execute the query using sqlcommand

public void executeSqlfileincsharp(string connectionStringName, string executesqlFileName)
  {
string sqlConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ToString();
FileInfo file = new FileInfo(executesqlFileName);
string sqlString = file.OpenText().ReadToEnd();
using (SqlConnection mySqlConnection = new SqlConnection(sqlConnectionString))
{
string[] spliter = { Environment.NewLine, " GO ", Environment.NewLine };
string[] sqlArrayString = sqlString.Split(spliter, StringSplitOptions.RemoveEmptyEntries);
string executeString = "";
for (int i = 0; i < sqlArrayString.Length; i++)
    {
  executeString = executeString + " " + sqlArrayString[i].ToString();
 }
using (SqlCommand mySqlCommand = mySqlConnection.CreateCommand())
{
 mySqlCommand.CommandText = executeString;
 mySqlConnection.Open();
 mySqlCommand.ExecuteNonQuery();
}
}
}

Tuesday, May 15, 2012

What is a partial class and how to use in c sharp

It was introduced under 2.0 framework which allows you to split a class o n to multiple files
Advantages:
Splitting huge volumes of code into multiple files which makes managing easier.Allows multiple programmers to work on the same class at the same time.grouping related code of a class in separate files
Here i will show how to develop a partial class in csharp.For this add a class to the project naming it as File1.cs and write the following code
partial class parts
{
public void test1()
{
Console.Writeline("method1");
}
public void test2()
{
Console.Writeline("method2");
}
}
add one more class naming it as File2.cs
 partial class parts { public void test3() { Console.Writeline("method3"); } public void test4() { Console.Writeline("method4"); } } Now to test the class add one more class to the project naming it as test parts.cs and write the following class testparts { static void main() { parts p= new parts(); p.test1(); p.test2(); p.test3(); p.test4(); Console.ReadLine();
} }

Monday, May 7, 2012

How to manipulate the gridview cell

Here i will show how to manipulate the grid view cell styles in windows forms application.For this i will get all grid view rows and compare the grid view header cell value with drop down selected value. Then the related data cells back colour will be changed to Green.In foreach loop we have one more for loop to get the entire column cells of related header in grid view.

foreach(DataGridViewRow row in this.Gvorders.Rows)
{
if (row.HeaderCell.Value == txtorder.Text)
{
for (int i = 0; i < Gvorders.Columns.Count; i++)
{
this.Gvorders.CurrentCell = row.Cells[i];
row.Cells[i].Style.BackColor = Color.Green;
}
}
}
VB:
For Each row As DataGridViewRow In Me.Gvorders.Rows
 If row.HeaderCell.Value = txtorder.Text Then
  For i As Integer = 0 To Gvorders.Columns.Count - 1
   Me.Gvorders.CurrentCell = row.Cells(i)
   row.Cells(i).Style.BackColor = Color.Green
  Next
 End If
Next

Friday, April 27, 2012

pass variable from codebehind to aspx (client side) in asp.net || pass value from server side to client side in Asp.net

In previous post i have given how to pass the variable value from client side  to server side (code behind).Now i will show how to pass the variable from code behind to aspx .Here i would not use any javascript or etc.Because there is so many ways to get the values to javascript variables from code behind.This process easy to understand for developers and who has not much knowledge in javascript.
<form  method="post" action="Calculation.aspx">
    <input id="h1" type="hidden" name="cart"  value="<%=strEncoded %>"/>
    <input id="h2" type="hidden" name="signature" value="<%=sign %>"/>
    <input type="button" name="submit"/>
</form>
When ever we assign the values to html control ,Those should be declare as "public" variable.Here the strEncoded,sign are passed to client side using "<%= >"
 public String strEncoded;
 public string sign;
//page_load
 strEncoded = "Encode string";
 sign= "teststring";

Thursday, March 15, 2012

How to change the array size at runtime in c#

Here i will show how to accept array size at run time and accepting elements in asp.net,Providing size of array at run time called"Dynamic array".This can be implemented in vb.net using "ReDim statement".
For the performance based static array provides better performance compare with custom array.The dynamic array should be used when array size changed at run time

c#:
submain();
byte[] a = null;
byte n = 0;
byte i = 0;
FileSystem.WriteLine("enter arrary size:");
n = ReadLine();
a = new byte[n];
FileSystem.WriteLine("Enter Elelments");
for (i = 0; i <= a.lenth - 1; i++) {
 a[i] = ReadLine;
}
VB:
submain()
Dim a() as byte
Dim n,i as byte
writeline("enter arrary size:")
n=ReadLine()
ReDim a(n-1)
WriteLine("Enter Elelments")
for i=0 to a.lenth-1
a(i)=ReadLine
Next

Bel