Monday, December 16, 2013

How to sort the gridview data ASP.Net?

protected void gvManageList_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                gvManageList.EditIndex = -1; 
                string sortExpression = e.SortExpression;
                if (GridViewSortDirection == SortDirection.Ascending)
                {
                    GridViewSortDirection = SortDirection.Descending;
                    BindManageListGrid(sortExpression, " DESC ");
                }
                else
                {
                    GridViewSortDirection = SortDirection.Ascending;
                    BindManageListGrid(sortExpression, " ASC ");
                }
                
            }
            catch (Exception ex)
            {
                ex.HandleException(ExceptionLayer.UI);
                Response.Redirect("CustomError.aspx", false);
            }
        }

        private SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = SortDirection.Ascending;
                return (SortDirection)ViewState["sortDirection"];
            }
            set
            {
                ViewState["sortDirection"] = value;
            }
        }

        public void BindManageListGrid(string sortby, string direction)
        {
            if (Session["ManageList"] != null)
            {
                DataTable dtList = Session["ManageList"] as DataTable;
                if (dtList.Rows.Count > 0)
                {
                    DataView dv = new DataView(dtList);
                    if (sortby.Length > 0)
                        dv.Sort = sortby + direction;
                    Session["ManageList"] = dv.ToTable();
                    gvManageList.DataSource = dv.ToTable();
                    gvManageList.DataBind();
                }
                else
                {
                    Session["ManageList"] = null;
                }
            }
           
        }

How to download file with open/save dialog box in ASP.Net?

if (File.Exists(strDestinationPath))
  {
    byte[] file = File.ReadAllBytes(strDestinationPath);

    // Create a memory stream from those bytes.
    using (MemoryStream memory = new MemoryStream(file))
        {
          Response.Clear();
          Response.ContentType = "application/octet-stream";
          Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(strDestinationPath));
          Response.AppendHeader("content-length", file.Length.ToString());
          Response.BinaryWrite(memory.ToArray());
          Response.Flush();
          Response.Close();
          //Response.End();
        }
  }
else
  {
    ShowPopupAlert("File Does not Exists");
    return;
  }

How to findcontrols on gridview RowCreated,RowDataBound,RowUpdating,RowDeleting,RowEditing and RowCommand?

protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lnkFile = (LinkButton)e.Row.FindControl("lnkFilePath");
                if (lnkFile != null)
                    ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(lnkFile);
            }
        }

protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
        {            
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    ImageButton btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                    if (btnDelete != null)
                        btnDelete.Attributes.Add("onclick", "javascript:return  confirm('Are you sure you want to delete this record?');");
  }
 }

protected void Gridview1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {            
                GridViewRow row = Gridview1.Rows[e.RowIndex];             
                TextBox txtDesc = (TextBox)row.Cells[0].FindControl("txtListValue");              
 }

protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
         Label lblListDesc = (Label)Gridview1.Rows[e.RowIndex].FindControl("lblListValue");
 }

protected void Gridview1_RowEditing(object sender, GridViewEditEventArgs e)
        {            
                Label lblIsActive = (Label)(Gridview1.Rows[Gridview1.EditIndex].FindControl("lblStatus"));
 }

protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
        {            
                GridViewRow grow = (GridViewRow)((Control)e.CommandSource).NamingContainer;                   
  Label lblTemp = (Label)grow.FindControl("lblDatatype");
 }

Monday, December 9, 2013

How to add postback trigger to a Gridview Button control?

 protected void gvViewUploadFile_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lnkFile = (LinkButton)e.Row.FindControl("lnkFilePath");
                if (lnkFile != null)
                    ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(lnkFile);
            }
        }

Tuesday, December 3, 2013

How to sort the Listbox using C#.Net?

//calling the function
 SortListBox(lstCountry);


public static void SortListBox(ListBox lbxId)
{
 List<ListItem> lstItem = new List<ListItem>();
 Comparison<ListItem>  compare = new Comparison<ListItem> (CompareListItems);

 //Iterate through each ListItem in the Listbox, and add them to the 'List' object
 foreach (ListItem lbItem in lbxId.Items)
  {
   lstItem.Add(lbItem);
  }

 //Sort the List
 lstItem.Sort(compare);

 //Clear the Listbox passed in, and add the sorted list from above
 lbxId.Items.Clear();
 lbxId.Items.AddRange(lstItem.ToArray());
}

public static int CompareListItems(ListItem li1, ListItem li2)
{
 //Return the strings in order that have been compared:
        return String.Compare(li1.Text, li2.Text);
}

How to retain the checkbox checked state in Gridview PageIndexChanging using ASP.Net?

How to retain the checkbox checked state in Gridview PageIndexChanging using ASP.Net?



List<int> arrSelectedItems; 

 protected void Page_Load(object sender, EventArgs e)
        {
             
                  arrSelectedItems = new List<int>();
              
        }

 protected void gvProductName_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                SaveCheckBoxState(); 
                gvProductName.PageIndex = e.NewPageIndex;
               
                if (ViewState["BindData"] != null)
                {
                    DataTable dtProduct = (DataTable)ViewState["BindData"];
                    gvProductName.DataSource = dtProduct;
                    gvProductName.DataBind(); 
                }

            }
            catch (Exception ex)
            {
                
            }
        }

private void SaveCheckBoxState()
        {
            if (arrSelectedItems != null)
            {
                if (ViewState["SaveState"] != null)
                {
                    arrSelectedItems = (List<int>)ViewState["SaveState"];
                }
                foreach (GridViewRow item in gvProductName.Rows)
                {
                    try
                    {
                        if (item.RowType == DataControlRowType.DataRow)
                        {
                            CheckBox chk = (CheckBox)(item.Cells[0].FindControl("chkSelect"));
                            if (chk.Checked)
                            {
                                if (!arrSelectedItems.Contains(Convert.ToInt32(gvProductName.DataKeys[item.RowIndex].Values["Product_Id"].ToString())))
                                    arrSelectedItems.Add(Convert.ToInt32(gvProductName.DataKeys[item.RowIndex].Values["Product_Id"].ToString()));
                            }
                            else
                            {
                                if (arrSelectedItems.Contains(Convert.ToInt32(gvProductName.DataKeys[item.RowIndex].Values["Product_Id"].ToString())))
                                    arrSelectedItems.Remove(Convert.ToInt32(gvProductName.DataKeys[item.RowIndex].Values["Product_Id"].ToString()));
                            }
                        }
                        ViewState["SaveState"] = arrSelectedItems;
                    }
                    catch (Exception ex)
                    {
                        
                    }
                }
            }
        }

        protected void gvProductName_PreRender(object sender, EventArgs e)
        {
            try
            {
                if (arrSelectedItems != null)
                {
                    arrSelectedItems = (List<int>)ViewState["SaveState"];
                    foreach (GridViewRow item in gvProductName.Rows)
                    {
                        if (item.RowType == DataControlRowType.DataRow)
                        {
                            CheckBox chkbox = (CheckBox)item.FindControl("chkSelect");
                            if (arrSelectedItems != null)
                            {
                                if (arrSelectedItems.Contains(Convert.ToInt32(gvProductName.DataKeys[item.RowIndex].Values["Product_Id"].ToString())))
                                {
                                    chkbox.Checked = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
        }  

Tuesday, November 19, 2013

How to authenticate and add/remove files from the network shared path using C#.Net?

using System;


using System.Collections.Generic;

using System.Linq;

using System.Text;

using System;

using System.Runtime.InteropServices;

using BOOL = System.Boolean;

using DWORD = System.UInt32;

using LPWSTR = System.String;

using NET_API_STATUS = System.UInt32;



namespace ABC.ProjectName.Common

{

public class MultipleFileUpload : IDisposable

{

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]

internal struct USE_INFO_2

{

internal LPWSTR ui2_local;

internal LPWSTR ui2_remote;

internal LPWSTR ui2_password;

internal DWORD ui2_status;

internal DWORD ui2_asg_type;

internal DWORD ui2_refcount;

internal DWORD ui2_usecount;

internal LPWSTR ui2_username;

internal LPWSTR ui2_domainname;

}



[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]

internal static extern NET_API_STATUS NetUseAdd(

LPWSTR UncServerName,

DWORD Level,

ref USE_INFO_2 Buf,

out DWORD ParmError);



[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]

internal static extern NET_API_STATUS NetUseDel(

LPWSTR UncServerName,

LPWSTR UseName,

DWORD ForceCond);



private bool disposed = false;



private string sUNCPath;

private string sUser;

private string sPassword;

private string sDomain;

private int iLastError;



///

/// The last system error code returned from NetUseAdd or NetUseDel. Success = 0

///

public int LastError

{

get { return iLastError; }

}



public void Dispose()

{

if (!this.disposed)

{

NetUseDelete();

}

disposed = true;

GC.SuppressFinalize(this);

}



///

/// Connects to a UNC path using the credentials supplied.

///

/// Fully qualified domain name UNC path

/// A user with sufficient rights to access the path.

/// Domain of User.

/// Password of User

/// True if mapping succeeds. Use LastError to get the system error code.

public bool NetUseWithCredentials(string UNCPath, string User, string Domain, string Password)

{

sUNCPath = UNCPath;

sUser = User;

sPassword = Password;

sDomain = Domain;

return NetUseWithCredentials();

}



private bool NetUseWithCredentials()

{

uint returncode;

try

{

USE_INFO_2 useinfo = new USE_INFO_2();



useinfo.ui2_remote = sUNCPath;

useinfo.ui2_username = sUser;

useinfo.ui2_domainname = sDomain;

useinfo.ui2_password = sPassword;

useinfo.ui2_asg_type = 0;

useinfo.ui2_usecount = 1;

uint paramErrorIndex;

returncode = NetUseAdd(null, 2, ref useinfo, out paramErrorIndex);

iLastError = (int)returncode;

return returncode == 0;

}

catch

{

iLastError = Marshal.GetLastWin32Error();

return false;

}

}



///

/// Ends the connection to the remote resource

///

/// True if it succeeds. Use LastError to get the system error code

public bool NetUseDelete()

{

uint returncode;

try

{

returncode = NetUseDel(null, sUNCPath, 2);

iLastError = (int)returncode;

return (returncode == 0);

}

catch

{

iLastError = Marshal.GetLastWin32Error();

return false;

}

}





///

/// Ends the connection to the remote resource

///

/// True if it succeeds. Use LastError to get the system error code

public bool NetOptionMethod()

{

uint returncode;

try

{

returncode = NetUseDel(null, sUNCPath, 2);

iLastError = (int)returncode;

return (returncode == 0);

}

catch

{

iLastError = Marshal.GetLastWin32Error();

return false;

}

}

}

}



==============Calling the function====================



public string UploadDocument(string strAction,string strSourcePath,string strDestFileName)

{

//MultipleFileUpload unc = new MultipleFileUpload();

string strDomain = ConfigurationManager.AppSettings["Domain"].ToString();

string strUserId = ConfigurationManager.AppSettings["Userid"].ToString();

string strPwd = ConfigurationManager.AppSettings["Password"].ToString();

string strDestinationPath = ConfigurationManager.AppSettings["DestinationPath"].ToString();

using (MultipleFileUpload unc = new MultipleFileUpload())

{

if (unc.NetUseWithCredentials(strDestinationPath, strUserId, strDomain, strPwd))

{

strDestinationPath = strDestinationPath + "\\" + strDestFileName + "_" + Path.GetFileName(strSourcePath);



if (strAction == "ADD")

{

if(File.Exists(strSourcePath))

File.Move(strSourcePath, strDestinationPath);

}

else if (strAction == "DELETE")

{

if (File.Exists(strSourcePath))

File.Delete(strSourcePath);

}

}

}





return strDestinationPath;

}



Friday, March 16, 2012

How to find the working days records in a month using SQL Server?

SELECT ActualTransactionDate FROM SubjectTransaction WHERE DATEPART(dw, ActualTransactionDate) IN (1, 7) and DATEPART (MONTH, ActualTransactionDate) IN (2)--Feb

Tuesday, February 21, 2012

How do I increase the connection limit for IIS 5.1 on Windows XP?

Make a command prompt window (start, run, cmd.exe) and issue these commands.

Step 1: cd \inetpub\adminscripts
Step 2: cscript adsutil.vbs set w3svc/MaxConnections 40
Step 3: iisreset

How to get the all time zone using C#.Net?

public static DataTable GetTimeZoneTable(bool caseSensitive)
{
var systemTimeZones = TimeZoneInfo.GetSystemTimeZones();
string displayName = string.Empty;
DataTable dt = new DataTable("timezones");
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("DisplayName", typeof(string));
dt.Columns.Add("BaseUtcOffsetMinutes", typeof(int));
dt.Columns.Add("SupportsDaylightSavingTime", typeof(bool));
dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"] };

foreach (TimeZoneInfo timeZone in systemTimeZones)
{
displayName = timeZone.DisplayName;
if (!caseSensitive) { displayName = displayName.ToLower(); }
dt.Rows.Add(timeZone.Id, displayName, Convert.ToInt32(timeZone.BaseUtcOffset.TotalMinutes), timeZone.SupportsDaylightSavingTime);
}
dt.AcceptChanges();
return dt;
}

----------

DatatTabe dt = GetTimeZoneTable(true);
 
Feedback Form