Sie sind auf Seite 1von 15

Creating a ThumbNail Image on Fly

This sample code shows how to create a ThumbNail image of width and Height 250 X
250 and save the Thumbnail Image in the Images folder of the Application.
private void SaveThumbNail (string folder, string filename)
{
System.Drawing.Image image =
System.Drawing.Image.FromFile(folder + filename);
System.Drawing.Image thumbnailImage =
image.GetThumbnailImage(250, 250, new
System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);
string thumbnailPath = folder + "\Thumbnail.JPG";
thumbnailImage.Save(thumbnailPath,
System.Drawing.Imaging.ImageFormat.Jpeg);
}
///
/// Required, but not used
///
/// true
public bool ThumbnailCallback()
{
return true;
}

Add an image dynamically


You can add an image dynamically with code below. using this ypu can also crate td(table
cell) dymaically and add to the tr. for that you have to give the id for tr and set the
property for runatserver=true.

int tdcount = 0;
//get the count of table cells in tr
tdcount = tr1.Controls.Count;
//Create a new table cell
HtmlTableCell tdcell = new HtmlTableCell();
//Create a new image control
Image img = new Image();
//set the url for image
img.ImageUrl = "C:\img.jpg";
img.Width = 120; //set the image width
img.Height = 100; //set the image hight
tdcell.ColSpan = 3; //set the colspan for table cell
tdcell.RowSpan = 4; //set the rowspan for table cell
tdcell.Controls.Add(img); // place image in table cell
tr1.Controls.AddAt(tdcount, tdcell); // Add table cell to the
table row.

DropDownList controls in a Gridview


The sample code load values in dropdown2(dd2) based on the selected value in
dropdown1(dd1)
The code below is that of an .aspx page that contains the DropDownList controls in a
GridView control
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=false
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnSelectedIndexChanging="GridView1_SelectedIndexChanging">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
DropDown 1
</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList ID="dd1" runat=server DataSource='<
%#Load_DropDown()>' DataTextField="brand_name" DataValueField="brand_id"
OnSelectedIndexChanged="Populate_Grid2" AutoPostBack=true>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
DropDown 2
</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList ID="dd2" runat=server
DataTextField="brand_name" DataValueField="brand_id"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

The code behind page handles the event that populates data in GridView

//function to determine which one is selected in dd1


protected void Populate_Grid2(object sender, EventArgs e)
{
//locate the row in which the dropdown value has been changed
GridViewRow gr=(GridViewRow)((DataControlFieldCell)
((DropDownList)sender).Parent).Parent;
//find the control in that
DropDownList d1=(DropDownList) gr.FindControl("dd1");
string selectedvalue=d1.selectedvalue;
//using selectedvalue execute a query like

//select * from product where brand_id=selectevalue


//get the result in datatable dt
//located the second dropdown(dd2)
DropDownList d2 = (DropDownList)gr.FindControl("dd2");
d2.DataSource = dt;
d2.DataBind();
}

Recheck checkboxes in Asp.net Gridview


//Namespace Reference
using System.Collections;
///
/// method to repopulate selected items in the GridView
/// NOTE: This is so if the user pages back to page they've been
/// to the selected items on that page are still selected
///
private void RePopulateCheckedItems(GridView grid, string ctrl)
{
ArrayList checkedItems = new ArrayList();
string chkBoxIndex;
CheckBox chk;
checkedItems = (ArrayList)Session["CheckedItems"];
//make sure we have selected items
if (!(checkedItems == null))
{
//loop through each row in the GridView
foreach (GridViewRow row in grid.Rows)
{
//get the index of each row
chkBoxIndex = (string)grid.DataKeys[row.RowIndex].Value.ToString();
//check to see if that index is in our ArrayList
if (checkedItems.Contains(chkBoxIndex))
{
//find the CheckBox column since it's in the ArrayList
chk = (CheckBox)row.FindControl(ctrl);
//check the CheckBox
chk.Checked = true;
}
//results = (string[])checkedItems.ToArray(typeof(string));
////now create our delimited string

//chkdItems = string.Join(",", results);


}
}
}

How to do Edit, Update, Delete in a GridView


The following code sample shows how to do Edit, Update, Delete in a GridView
public partial class AllinGridView : System.Web.UI.Page
{
search_user sh = new search_user();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindall();
}
}
public void bindall()
{
DataSet ds = sh.show_all_details();
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindall();
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindall();
}
protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindall();
}
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
int id = (int)GridView1.DataKeys[e.RowIndex].Value;
sh.get_userid = id;
TextBox tx1=(TextBox)
(GridView1.Rows[GridView1.EditIndex].Cells[0].FindControl("TextBox1"));
TextBox tx2=(TextBox)
(GridView1.Rows[GridView1.EditIndex].Cells[1].FindControl("TextBox2"));
TextBox tx3=(TextBox)
(GridView1.Rows[GridView1.EditIndex].Cells[2].FindControl("TextBox3"));

sh.get_username = tx1.Text;
sh.get_location = tx2.Text;
sh.get_contactno = tx3.Text;
sh.update_search();
GridView1.EditIndex = -1;
bindall();
}
protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
int id = (int)GridView1.DataKeys[e.RowIndex].Value;
sh.get_userid = id;
sh.delete_search();
bindall();
}
}

Binding XML Data to the GridView


This code sample binds XML data to a GridView control, by using
DataTable.ReadXML() function.
The below code shows a simple example of binding the GridView control dynamically.
The GridView control here is nested.
The code samples have .aspx page followed by the code-behind file.

<form id="form1" runat="server">


<div>
<asp:GridView runat="server" ID="Grd"
AutoGenerateColumns="false" OnRowDataBound="OnDataBound">
<Columns>
<asp:BoundField DataField="agent_cd" HeaderText="Agent
Cd" />
<asp:TemplateField HeaderText ="Agent Details">
<ItemTemplate>
<asp:GridView ID="ChldGrid" runat="server">
<Columns>
<asp:BoundField DataField="agent_name"
HeaderText="Agent Cd" />
<asp:BoundField DataField="address1"
HeaderText="Address" />
<asp:BoundField DataField="city"
HeaderText="City" />
<asp:BoundField DataField="state"
HeaderText="State" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>

</asp:GridView>
</div>
</form>

The following code is the code-behind C# file for the above .aspx page.
//Code for binding the GridView
using System;
using System.Data;
using System.Data.SqlClient;
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 NestedGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
try
{
SqlConnection conn = new SqlConnection("");
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter ADA = new SqlDataAdapter("", conn);
ADA.Fill(dt);
Grd.DataSource = dt;
Grd.DataBind();

}
catch (Exception E)
{
string str = E.Message;
}

}
protected void OnDataBound(object sender , GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView Grd = (GridView)e.Row.FindControl("ChldGrid");
DataTable dt = new DataTable("TEST");
dt.Columns.Add("agent_cd");
dt.Columns.Add("agent_name");
dt.Columns.Add("address1");

}
}

dt.Columns.Add("city");
dt.Columns.Add("state");
dt.ReadXml(Server.MapPath("Data.xml"));
Grd.DataSource = dt;
Grd.DataBind();

Give below is a sample XML Content that can be used to test the program. Save this
content as a .xml file.
<?xml version="1.0" standalone="yes"?>
<DocumentElement>
<TEST>
<agent_cd>00000026</agent_cd>
<agent_name>TROPIC ICE INCORPORATED</agent_name>
<address1>2805 N COMMERCE PKWY</address1>
<city>MIRAMAR</city>
<state>FL</state>
</TEST>
</DocumentElement>

Uploading and Downloading files


Add the following code in html page
<form id="form1" runat="server">
<table style="z-index: 103; left: 94px; position: absolute; top:
71px">
<tr>
<td>
<input id="txtFileContents" type="file" runat="server"
name="FileUpload"/>
</td>
</tr>
<tr>
<td align="right">
<asp:button id="btnUpload" Text="Upload" Runat="server"
OnClick="btnUpload_Click" ></asp:button>
</td>
</tr>
</table>
<asp:GridView ID="gvFiles" runat="server" Style="z-index: 104;
left: 90px; position: absolute;
top: 150px" CellPadding="4" ForeColor="#333333"
GridLines="None" OnSelectedIndexChanged="gvFiles_SelectedIndexChanged">
<Columns>
<asp:TemplateField ShowHeader="False">

<ItemTemplate >
<asp:LinkButton ID="lnkDownload"
ForeColor="DarkOrange" runat="server" CausesValidation="False"
CommandName="Select"
Text="Download"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True"
ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</form>

Add the following code in code file


-----------------------------------protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Fill();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string strFileName =
txtFileContents.PostedFile.FileName.Substring(txtFileContents.PostedFile
.FileName.LastIndexOf("\\") + 1);
string strFileType = txtFileContents.PostedFile.ContentType;
int intFileLen = txtFileContents.PostedFile.ContentLength;
Stream objStream = txtFileContents.PostedFile.InputStream;
byte[] bytFile = new byte[intFileLen];
objStream.Read(bytFile, 0, intFileLen);

50);

SqlCommand cmdUploadFile = new SqlCommand("sp_Files", sqlConn);


cmdUploadFile.CommandType = CommandType.StoredProcedure;
cmdUploadFile.Parameters.Add("@FileName ", SqlDbType.VarChar,
cmdUploadFile.Parameters.Add("@Files", SqlDbType.Image);
cmdUploadFile.Parameters.Add("@FileType", SqlDbType.VarChar,

50);

cmdUploadFile.Parameters[0].Value = strFileName;
cmdUploadFile.Parameters[1].Value = bytFile;
cmdUploadFile.Parameters[2].Value = strFileType;
sqlConn.Open();
cmdUploadFile.ExecuteNonQuery();
sqlConn.Close();
Fill();
}
protected void gvFiles_SelectedIndexChanged(object sender, EventArgs
e)

string strId = gvFiles.SelectedRow.Cells[1].Text;


SqlCommand cmd = new SqlCommand("select FileType,Files,FileName
from Files where id=" + strId + "", sqlConn);
sqlConn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string strFileType = dr[0].ToString();
string strFileName = dr[2].ToString();
//if below statement is not there, it will not effect the
operation
Response.ContentType = strFileType;
Response.AddHeader("content-disposition",
"attachment;filename=" + strFileName + "");
Response.BinaryWrite((byte[])dr[1]);
Response.End();

}
sqlConn.Close();

public void Fill()


{
SqlDataAdapter sdaFiles = new SqlDataAdapter("select
id,FileType,Files,FileName from Files", sqlConn);
DataSet dsFiles = new DataSet();
sdaFiles.Fill(dsFiles);
gvFiles.DataSource = dsFiles;
gvFiles.DataBind();
}

How to do Grid view sorting


The following code sample shows how to do sorting in grid view
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = grid.DataSource as DataTable;

if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = GetSortExpression(e.SortExpression);
grid.DataSource = dataView;
grid.DataBind();
}
}
private string GetSortExpression(string sortExpression)
{
if (sortExpression == GridViewSortExpression && GridViewSortDirection
== "ASC")
{
GridViewSortDirection = "DESC";
}
else
{
GridViewSortDirection = "ASC";
}
GridViewSortExpression = sortExpression;
return sortExpression + " " + GridViewSortDirection;

paging, sorting, link button in GridView


This code is for Aspx page:
In this code i have used NorthWind Database
asp:GridView ID="grcoll" runat="server" AutoGenerateColumns="false"
DataKeyNames="orderId"
CssClass="mygrid" Width="100%" HeaderStyle-BackColor="white" BorderWidth="1"
RowStyle-BorderWidth="0" AllowPaging="true" AllowSorting="true" PageSize="20"
OnRowDataBound="grcoll_OnRowDataBound"
OnRowCommand="grcoll_OnRowCommand"

OnPageIndexChanging="grcoll_PageIndexChanging"
PagerStyle-HorizontalAlign="Center" OnSorting="grcoll_Sorting"
Columns
asp:BoundField DataField="OrderId" SortExpression="OrderId" HeaderText="Order Id"
HeaderStyle-ForeColor="#78776b"
asp:BoundField DataField="OrderDate" SortExpression="OrderDate"
HeaderText="Order Date" HeaderStyle-ForeColor="#78776b"
asp:BoundField DataField="ShippedDate" SortExpression="ShippedDate"
HeaderText="Shipped Date" HeaderStyle-ForeColor="#78776b"
asp:TemplateField HeaderText="Action"
ItemTemplate
asp:LinkButton CssClass="links" ID="lnkView" runat="server" Text="View"
CommandName="viewOrder" CommandArgument='<%#Eval("OrderId") %>'
/ItemTemplate
/asp:TemplateField
/Columns
/asp:GridView

now here is the code for aspx.cs


public partial class OrderDetail : System.Web.UI.Page
{
static string m_ConnectionString =
System.Configuration.ConfigurationManager.AppSettings["conString"].ToString();
static string sort = "asc";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request["custId"] != null)
{

bindGrid("OrderId", sort);
//bindGrid();
bindCutomerDetail();
}
}
}
protected void bindCutomerDetail()
{
try
{
string sql = "select * from Customers where customerId='" +
Request["custId"].ToString() + "'";
SqlDataReader dr = DBAccess.ExecuteReader(m_ConnectionString,
CommandType.Text, sql);
if (dr.HasRows)
{
dr.Read();
lblAddress.InnerHtml = dr["address"].ToString();
lblax.InnerHtml = dr["fax"].ToString();
lblCity.InnerHtml = dr["city"].ToString();
lblCompanyName.InnerHtml = dr["CompanyName"].ToString();
lblContactName.InnerHtml = dr["ContactName"].ToString();
lblContactTitle.InnerHtml = dr["ContactTitle"].ToString();
lblCountry.InnerHtml = dr["Country"].ToString();
lblPhone.InnerHtml = dr["phone"].ToString();
lblPostalCode.InnerHtml = dr["postalCode"].ToString();
lblRegion.InnerHtml = dr["region"].ToString();
}
dr.Dispose();
dr.Close();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
protected void bindGrid(string column, string expression)
{
lblcustomerId.Text = Request["custId"].ToString();
string sql = "select orderId,orderDate,shippedDate from Orders where CustomerId='" +
Request["custId"].ToString() + "'";
DataSet ds = DBAccess.ExecuteDataset(m_ConnectionString, CommandType.Text, sql);
DataView dv = new DataView(ds.Tables[0]);
dv.Sort = column + " " + expression;

grcoll.DataSource = dv;
grcoll.DataBind();
if (ds.Tables[0].Rows.Count > 0)
{
}
else
{
lblmsg2.Text = "No records Found";
}
}
protected void grcoll_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
}

protected void grcoll_OnRowCommand(object sender, GridViewCommandEventArgs e)


{
if (e.CommandName == "viewOrder")
{
string OrderId;
OrderId = Convert.ToString(e.CommandArgument);
Response.Redirect("OrderDescription.aspx?OrderId=" + OrderId);
}
}
protected void grcoll_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//This try block is used for Page Indexing
try
{
grcoll.PageIndex = e.NewPageIndex;
bindGrid("OrderId", sort);
}
catch (Exception ex)
{
//AppLib.SendErrorMail(ex.ToString());
// Response.Redirect("error.aspx");

}
}
protected void grcoll_Sorting(object sender, GridViewSortEventArgs e)
{
if (sort == "asc")
{
bindGrid(e.SortExpression, "desc");
sort = "desc";
}
else
{
bindGrid(e.SortExpression, "asc");
sort = "asc";
}
}
}

How to get a seelcted row from gridview on button click uisng row
command event in c#
This small code will help some body for fetch the data from different controls in a
gridview.
I have created a gridview and bind it with 3 data bound column(id,name and age) from
sql datasource . i have added a button field (its not a template column) with button type as
last column .so when i click the button aganist on each row the other column values on
corrosponding row should be fetched.
I have Mapped the follwing procedure (MyGridview_RowCommand)to RowCommand
Event through property box of grid view.
For button field (last column of gridview)i have given the name "FindValue" as
CommandName for conditional running of code at runtime.
protected void MyGridview_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "FindValue")
{
GridViewRow row =
((GridView)e.CommandSource).Rows[Convert.ToInt32(e.CommandArgument)];
string id = ((Label)(row.FindControl("label1"))).Text;
string name = ((Label)(row.FindControl("Label2"))).Text;
}
}

Hashtable - basic operations


The code sample in C# explains the basic operations on a Hashtable. A Hashtable is an
object that stores (key,value) pairs. With such an object, storing and searching data
becomes easier.
The example describes operations such as - creation of a Hashtable, inserting data,
accessing data from a hashtable and deleting values.

using System.Collections; //for hashtable


//Create a Hashtable
Hashtable ohash = new Hashtable();
//Add data using the Add() method
ohash.Add("US", "UNITED STATE");
ohash.Add("IN", "INDIA");
ohash.Add("PAK", "PAKISTAN");
//value are stored in key and value pair in hashtable
//to fetch the value we use key name, for example
string countryName = ohash["US"].ToString();
//to delete any record, we will also use key name, for example
ohash.Remove("US");
//now to fetch all the values from hashtable
IDictionaryEnumerator oIDic = ohash.GetEnumerator();
while (oIDic.MoveNext())
{
Response.Write(oIDic.Value.ToString());
}

Das könnte Ihnen auch gefallen