Wael Sayed

Wael Sayed

Monday, September 22, 2008

Free Asp.Net For All: How to Sort GridView by code

Free Asp.Net For All: How to Sort GridView by code

How to Sort GridView by code

hello , In this article we will discuss in sorting gridview .

Sorting gridview very easy if you connected with dataset typed or SqlDataSource etc.. But it's not similar if you retrieve your data by DAL(Data Access layer) or method returns a collection of data.

In this example we use DataView to sort data

let's start

1- Drag a gridView on a simple page (GridPersons)


2- create a method returns DataView object to populated gridview



public DataView GetDate()
{
using (SqlConnection con = new SqlConnection("Server=.;DataBase=AdventureWorks;integrated security=SSPI;"))
{
try
{
SqlCommand com = con.CreateCommand();
com.CommandText = "Select FirstName , LastName,EmailAddress from person.Contact";
con.Open();
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = com;
DataSet ds = new DataSet();
dap.Fill(ds);
DataTable personTable = ds.Tables[0];
DataView dv = new
DataView(personTable);

if (ViewState["sortExpr"] != null && ViewState["OrderBy"] != null)
{
if (ViewState["OrderBy"].ToString() == "Desc")
{
ViewState["OrderBy"] = "Asc";
}
else
{
ViewState["OrderBy"] = "Desc";
}

dv.Sort = (string)ViewState["sortExpr"] + " " + (string)ViewState["OrderBy"];
}
return dv;
}
finally
{
con.Dispose();
}
}
}

3- Add GridView Sorting Event and write this code



protected void GridPersons_Sorting(object sender, GridViewSortEventArgs e)
{
ViewState["sortExpr"] = e.SortExpression;
Session["EditMode"] = null;
if (ViewState["OrderBy"] == null)
{
ViewState["OrderBy"] = "Desc";
}
GridPersons.DataSource = GetDate();
GridPersons.DataBind();
}

4- In Page Load add this code


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridPersons.DataSource = GetDate();
GridPersons.DataBind();
}
}


How to Check all checkboxes in a GridView

In this article we will discuss in how to fire all checkBoxes in gridview at once , we need to do that when deleting all rows in gridView .

So let's start to do this task

1- Add SqlDataSource for conection to dataBase in this example we use AdventureWorksDW database .


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksDWConnectionString %>"
SelectCommand="SELECT [FirstName] FROM [DimEmployee]"></asp:SqlDataSource>

2- after drag the gridview in Asp.net page change the property of AutoGenerateColumns to false

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="442px" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="ChkAll" runat="server" AutoPostBack="True"
oncheckedchanged="Chk_CheckedChanged" Text="Check All" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("FirstName") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
3- Now we have 2 checkboxes inside gridview the first on for check or uncheck all rows and the 2nd for check or un check per row.
4- double click on 'chkAll' checkBox and write this code :

protected void Chk_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
foreach (Control c in GridView1.Controls)
{
string value = c.ID;
}
CheckBox chkSelect = ((CheckBox)row.FindControl("chkSelect"));
if (((CheckBox)sender).Checked == true)
{
chkSelect.Checked = true;
}
else
{
chkSelect.Checked = false;
}
}
}
}

Saturday, September 20, 2008

How to set Custom Size for uploading

Sometimes we need to avoid large files from users, when upload photos, documents, mp3 files ...etc
In this article we validate files size to avoid users upload large size and customize a limit size for uploading files

First we need to add this lines in web.config file



So we change it to 200000
After Adding FileUpload control in the page add this code to button upload event



// Note : Custom size is 4 Mg


protected void Button1_Click(object sender, EventArgs e)
{

string filepath =Server.MapPath("~\\Upload");
HttpFileCollection uploadedFiles = Request.Files;
for (int i = 0; i < userpostedfile =" uploadedFiles[i];"> 0)
{
if ((userPostedFile.ContentLength / 1024) / 1024 > 4)
{
Label1.Text = "Max Size";
}
else
{
userPostedFile.SaveAs(filepath + "\\" +
System.IO.Path.GetFileName(userPostedFile.FileName));
}
}
}


Friday, September 19, 2008

How to set files validation on FileUpload


In this Article we will discuss how to set validation when upload files by File upload control .



In this example we use RegularExpressionValidator control



Note : in this example we validate mp3 files so the user can select just mp3 files

How to use Upload file control with UpdatePanal

In this Article we will Add upload file in a simple page works by ajax.Net.
Many developers faces a problems when add upload file control in an updatepanal control.Here is a simple code to avoid these problems In Html code add file upload control inside updatepanal then add PostBackTriggerAnd bind the upload button with the trigger as following:

In the Code behind, add the following lines of code:-
protected void Button1_Click(object sender, EventArgs e)
{
string filepath =Server.MapPath("~\\Upload");
HttpFileCollection uploadedFiles = Request.Files;
for (int i = 0; i <>
{
HttpPostedFile userPostedFile = uploadedFiles[i];
if (userPostedFile.ContentLength > 0)
{
if ((userPostedFile.ContentLength / 1024) / 1024 > 4)
{
Label1.Text =
"Max Size";
}
else
{
userPostedFile.SaveAs(filepath + "\\" +System.IO.Path.GetFileName (userPostedFile.FileName));
}
}
}
}
-----------------------------------------------------------