2011/09/20

How to edit gridview in asp.net


public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=test;integrated security=true;");
    SqlDataAdapter adp;
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ViewState["exp"] = "name";
            datab();
        }
    }
    private void datab()
    {
        adp = new SqlDataAdapter("select * from emp order by " + ViewState["exp"].ToString(), cn);
        adp.Fill(ds, "first");
        GridView1.DataSource = ds;
        GridView1.DataBind();

    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        datab();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        datab();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string str;
        str = GridView1.DataKeys[e.RowIndex].Value.ToString();

        cn.Open();
        SqlCommand cmd = new SqlCommand("delete from emp where name=@name", cn);
        cmd.Parameters.AddWithValue("@name", str);
        cmd.ExecuteNonQuery();
        cn.Close();

        GridView1.EditIndex = -1;
        datab();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string str;
        str = GridView1.DataKeys[e.RowIndex].Value.ToString();

        cn.Open();
        SqlCommand cmd = new SqlCommand("update emp set name=@name,age=@age,city=@city where name=@org_name", cn);
        TextBox t1, t2, t3;
        t1 =(TextBox) GridView1.Rows[e.RowIndex].FindControl("TextBox1");
        t2 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
        t3 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3");  

        cmd.Parameters.AddWithValue("@name", t1.Text );
        cmd.Parameters.AddWithValue("@age", t2.Text );
        cmd.Parameters.AddWithValue("@city", t3.Text );
        cmd.Parameters.AddWithValue("@org_name", str);
        cmd.ExecuteNonQuery();
        cn.Close();

        GridView1.EditIndex = -1;
        datab();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.EditIndex = -1;
        datab();
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["exp"] = e.SortExpression.ToString();
        GridView1.EditIndex = -1;
        datab();
    }
}

2011/09/07

Add Month to a date in javascript

function getNextScheduledDate() {
            var date = document.getElementById('<%= txtDate.ClientID %>');
            var arry = new Array();
            arry[1] = document.getElementById('<%=txtDate.ClientID %>').value;
            var ArrDoj = arry[1].split("/");
            var myDate = new Date(ArrDoj[2], ArrDoj[1], ArrDoj[0]);
            //get month and add three month
            myDate.setMonth(myDate.getMonth() + 3);
            //get date
            var strday = myDate.getDate(); //.getDay();
            var strMonth = myDate.getMonth();
            //get year
            var strYear = myDate.getFullYear();
            VarifyMonth(strMonth, strYear, strday);
        }

        function VarifyMonth(currMonth, currYear, CurrDay) {

            if (currMonth > 12) {
                currMonth = 1;
                currYear = currYear + 1;
            }

            //            var ModDay;
            //            if (getNumFebDays(currYear) == 28 && currMonth == 2) {
            //                ModDay = 3;
            //            }

            //            if (getNumFebDays(currYear) == 29 && currMonth == 2) {
            //                ModDay = 2;
            //            }

            ModDateStr = CurrDay + "/" + currMonth + "/" + currYear;
            document.getElementById('<%=txtNextScheduleDate.ClientID %>').value = ModDateStr;
        }

        function getNumFebDays(theYear)      // calc num days in February
        {
            if ((theYear % 4 == 0 && theYear % 100 != 0) || theYear % 400 == 0)
                return 29;
            else
                return 28;
        }

2011/09/05

Multiple File Upload

HttpFileCollection uploadFilCol = Request.Files;
02.for(int i=0;i<uploadFilCol.Count;i++)
03.{
04.  HttpPostedFile file = uploadFilCol[i];
05.  string fileExt = Path.GetExtension(file.FileName).ToLower();
06.  string fileName = Path.GetFileName(file.FileName);
07.  if(fileName != string.Empty)
08.  {
09.    try
10.    {
11.      if(fileExt == ".jpg" || fileExt == ".gif")
12.      {
13.        file.SaveAs(Server.MapPath("./Images/") + fileName);
14.        this.ShowMessage(" " + fileName + " Successfully Uploaded",i);
15.      }
16.      else
17.      {
18.        file.SaveAs(Server.MapPath("./Others/") + fileName);
19.        this.ShowMessage(" " + fileName + " Successfully Uploaded",i);
20.      }
21.    }
22.    catch(Exception ex)
23.    {
24.      this.ShowMessage(" " + ex.Message, i);
25.    }
26.  }
27.}

2011/09/04

Fill Gridview using datatable in asp.net


 DataTable dt = new DataTable();
        if (Session["data"] != null)
        {
            dt = (DataTable)Session["data"];
        }
        else
        {
            dt.Columns.Add(new DataColumn("product", typeof(string)));
            dt.Columns.Add(new DataColumn("quantity", typeof(Int32 )));
            dt.Columns.Add(new DataColumn("price", typeof(Single )));
            dt.Columns.Add(new DataColumn("pdate", typeof(DateTime )));
        }

        DataRow dr;
        dr = dt.NewRow();
        dr["product"] = TextBox1.Text;
        dr["quantity"] = Convert.ToInt32( TextBox2.Text);
        dr["price"] = Convert.ToSingle(TextBox3.Text);
        dr["pdate"] = Convert.ToDateTime(TextBox4.Text).ToString("yyyy/MM/dd");
        dt.Rows.Add(dr);

        Session["data"] = dt;

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

2011/09/03

hey frds I want to fetch data from a column and display it as a row that's called pvorting !!!! may u pls help me out?


private DataTable PivotTable(DataTable origTable)
{
DataTable newTable = new DataTable();
DataRow dr = null;

//Add Columns to new Table
------------------------------
for (int i = 0; i <= origTable.Rows.Count; i++)
{
newTable.Columns.Add(new DataColumn(origTable.Columns[i].ColumnName, typeof(String)));
}
//Execute the Pivot Method
for (int cols = 0; cols < origTable.Columns.Count; cols++)
{
dr = newTable.NewRow();
for (int rows = 0; rows < origTable.Rows.Count; rows++)
{
if (rows < origTable.Columns.Count)
{
dr[0] = origTable.Columns[cols].ColumnName;
// Add the Column Name in the first Column
dr[rows + 1] = origTable.Rows[rows][cols];
}
}
newTable.Rows.Add(dr); //add the DataRow to the new Table rows collection
}
return newTable;
--------------------------------------------------------------------------
This method is used to fill grid view
------------------------------------------------
private void BindGridView()
{
try
{

string sqlStatement = "SELECT Top(5)* FROM Customers";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
//Bind the First GridView with the original data from the DataTable
GridView1.DataSource = dt;
GridView1.DataBind();

//Pivot the Original data from the DataTable by calling the
//method PivotTable and pass the dt as the parameter
DataTable pivotedTable = PivotTable(dt);
GridView2.DataSource = pivotedTable;
GridView2.DataBind();

}
}
catch (Exception ex)
{
lblMsg.Text="Error:"+ex.Message.ToString();
}

-------------------------------------------------------------------
You can call bindgrid method where u want.just i wnt to call in page load event
--------------------------
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridView();
}
}