顯示具有 Paging 標籤的文章。 顯示所有文章
顯示具有 Paging 標籤的文章。 顯示所有文章

2014年7月13日 星期日

[RESOLVED] Alphabetic Paging


Hi, Could you please help me on the issue of using the ASCII value of Georgian language characters. How can I change the english alphabet? I cannot retrive data since my contact list is in Georgian language. Here is the code:


public partial class alfabet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["CurrentAlphabet"] = "ALL";
this.GenerateAlphabets();
this.BindDataList();
}
}

public class Alphabet
{
private string _value;
private bool _isNotSelected;

public string Value
{
get
{
return _value;
}
set
{
_value = value;
}
}

public bool isNotSelected
{
get
{
return _isNotSelected;
}
set
{
_isNotSelected = value;
}
}
}

private void GenerateAlphabets()
{
List alphabets = new List();
Alphabet alphabet = new Alphabet();
alphabet.Value = "ALL";
alphabet.isNotSelected = !alphabet.Value
.Equals(ViewState["CurrentAlphabet"]);
alphabets.Add(alphabet);
for (int i = 65; i <= 90; i++)
{
alphabet = new Alphabet();
alphabet.Value = Char.ConvertFromUtf32(i);
alphabet.isNotSelected = !alphabet.Value
.Equals(ViewState["CurrentAlphabet"]);
alphabets.Add(alphabet);
}
rptAlphabets.DataSource = alphabets;
rptAlphabets.DataBind();
}

private void BindDataList()
{
string conStr = ConfigurationManager
.ConnectionStrings["CompanyInfoEventsConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("spx_GetContacts");
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Alphabet", ViewState["CurrentAlphabet"]);
con.Open();
dlContacts.DataSource = cmd.ExecuteReader();
dlContacts.DataBind();
con.Close();

if (ViewState["CurrentAlphabet"].ToString().Equals("ALL"))
lblView.Text = "all Contacts.";
else
lblView.Text = "Contacts whose name starts with "
+ ViewState["CurrentAlphabet"].ToString();
}

protected void Alphabet_Click(object sender, EventArgs e)
{
LinkButton lnkAlphabet = (LinkButton)sender;
ViewState["CurrentAlphabet"] = lnkAlphabet.Text;
this.GenerateAlphabets();
this.BindDataList();
}



}







Hi,


The ASCII value of the alphabets A-Z is 65 - 90 same way for Georgian language you need to set appropriate value.


#The ASCll Table:

http://www.asciitable.com/ . 


And I think this article may help you:

http://www.c-sharpcorner.com/uploadfile/satyapriyanayak/alphabetic-paging-using-gridview-control/ .


Best Regards,

Amy Peng 



[RESOLVED] Checkboxes in my gridview being unchecked don&#39;t remove value from Dictionary


We just uncovered an odd bug in this gridview with checkboxes. (original thread:
http://forums.asp.net/post/4691898.aspx) The idea is to store the checkboxes that are checked into a dictionary that has (username, boolean) in this case the key is username, the value is boolean. As I step
through the checkbox state, I'm wanting to make it so when someone unchecks a username checkbox, it gets stripped from the checkbox dictionary. It doesn't seem to be working. I'm using the viewstate to try to keep track of which checkboxes are checked. I guess
this is what I get for trying to use GridView with paging, ugh! Here's the code:


 


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblName = ((Label)e.Row.FindControl("lblName"));
DataRowView _dv = (DataRowView)e.Row.DataItem;
UserInformation _u = new UserInformation((string)_dv.Row["USER"], false);
if (_u.Name != null)
{
lblName.Text = _u.Name;
_u = null;
}
else
{
e.Row.Visible = false;
}
String id = (String)GridView1.DataKeys[e.Row.RowIndex].Value;
if (!_checkBoxDictionary.ContainsKey(id))
{
_checkBoxDictionary.Add(id, false);
}
CheckBox checkBox = (CheckBox)e.Row.FindControl("chkSelect");
checkBox.Checked = _checkBoxDictionary[id];
}
}

protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
_checkBoxDictionary = (Dictionary)ViewState["CheckBoxDictionary"];
}

protected override object SaveViewState()
{
ViewState["CheckBoxDictionary"] = _checkBoxDictionary;
return base.SaveViewState();
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
String id = (String)GridView1.DataKeys[row.RowIndex].Value;
CheckBox checkBox = (CheckBox)row.FindControl("chkSelect");
_checkBoxDictionary[id] = checkBox.Checked;
}
}



Solved the problem with a combination of what I found there and a little of my own coding handywork. Primarily, the answer to my problem was found at

http://www.codeproject.com/Articles/202938/How-to-select-multiple-records-from-the-GridView-a


[RESOLVED] hyperlink in gridview


hi there,


my site is using a gridview including a hyperlink column (select)


this works fine if you click select, all data located in that row will be transformed to a next page at the right spot; everything ok.


But if my gridview generates a number of rows, the following hyperlinks are not working, it shows only the 'select' text


but it is not click-able. The strange thing is that it worked fine the first time i build it.


what goes wrong in here?  it can't be a big thing


kind regards


Romano


            Width="1150px" AllowPaging="True" PageSize="14"
onpageindexchanging="GV_PageIndexChanging" AllowSorting="True"
BorderColor="#109DAA" BorderStyle="Solid" BorderWidth="2px">



ShowHeader="False" SortExpression="IMAGE">

Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />
Width="60px" CssClass="GVstyle" />


Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />
CssClass="GVstyle" Wrap="True" />


Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />



Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />



Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />


DataNavigateUrlFormatString="outputpage.aspx?IMAGE={0}&NAME={1}&CITY={2}&PROFESSION={3}&CATEGORY={4}&GENDER={5}&AGE={6}&STATES={7}&TELEPHONE={8}&EMAIL={9}&EMPLOYER={10}&YEARS={11}&EDUCATION={12}&MOTIVATION={13}&INFORMATION={14}"
Text="Select" >







Code behind


protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
DataBind();
}
}

private void BindData()
{
string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connstr);

DataSet DS = new DataSet();
DataTable members = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand SelectCommand = new SqlCommand();
SelectCommand.CommandType = CommandType.Text;

SelectCommand.CommandText = "SELECT NAME,GENDER,AGE,STATES,CITY,TELEPHONE,EMAIL,CATEGORY,PROFESSION,EMPLOYER,YEARS,EDUCATION,MOTIVATION,INFORMATION,IMAGE FROM members WHERE STATES = @STATES AND CATEGORY = @CATEGORY ";
SelectCommand.Connection = conn;

SelectCommand.Parameters.Add("@STATES",SqlDbType.VarChar).Value = DropDownList7.SelectedItem.Text;
SelectCommand.Parameters.Add("@CATEGORY",SqlDbType.VarChar).Value = DropDownList8.SelectedItem.Text;

da.SelectCommand = SelectCommand;
da.Fill(DS);
GV.DataSource = DS;
GV.DataBind();

if (GV.Rows.Count == 0)
{
errormessage.Text = "there are no members to be found, please try it again later";
}
if (GV.Rows.Count > 0)
{
errormessage.Text = "";
}

conn.Close();

}

protected void GV_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GV.PageIndex = e.NewPageIndex;
BindData();
}

protected void Button10_Click(object sender, EventArgs e)
{

BindData();
}

}



Usually, HyperLinkField not clickable because DataNavigateUrlFields has null value, check the data. Why not simply passing id value and get another values in another page based this id?

[RESOLVED] Alphabetic Paging


Hi, Could you please help me on the issue of using the ASCII value of Georgian language characters. How can I change the english alphabet? I cannot retrive data since my contact list is in Georgian language. Here is the code:


public partial class alfabet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["CurrentAlphabet"] = "ALL";
this.GenerateAlphabets();
this.BindDataList();
}
}

public class Alphabet
{
private string _value;
private bool _isNotSelected;

public string Value
{
get
{
return _value;
}
set
{
_value = value;
}
}

public bool isNotSelected
{
get
{
return _isNotSelected;
}
set
{
_isNotSelected = value;
}
}
}

private void GenerateAlphabets()
{
List alphabets = new List();
Alphabet alphabet = new Alphabet();
alphabet.Value = "ALL";
alphabet.isNotSelected = !alphabet.Value
.Equals(ViewState["CurrentAlphabet"]);
alphabets.Add(alphabet);
for (int i = 65; i <= 90; i++)
{
alphabet = new Alphabet();
alphabet.Value = Char.ConvertFromUtf32(i);
alphabet.isNotSelected = !alphabet.Value
.Equals(ViewState["CurrentAlphabet"]);
alphabets.Add(alphabet);
}
rptAlphabets.DataSource = alphabets;
rptAlphabets.DataBind();
}

private void BindDataList()
{
string conStr = ConfigurationManager
.ConnectionStrings["CompanyInfoEventsConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("spx_GetContacts");
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Alphabet", ViewState["CurrentAlphabet"]);
con.Open();
dlContacts.DataSource = cmd.ExecuteReader();
dlContacts.DataBind();
con.Close();

if (ViewState["CurrentAlphabet"].ToString().Equals("ALL"))
lblView.Text = "all Contacts.";
else
lblView.Text = "Contacts whose name starts with "
+ ViewState["CurrentAlphabet"].ToString();
}

protected void Alphabet_Click(object sender, EventArgs e)
{
LinkButton lnkAlphabet = (LinkButton)sender;
ViewState["CurrentAlphabet"] = lnkAlphabet.Text;
this.GenerateAlphabets();
this.BindDataList();
}



}







Hi,


The ASCII value of the alphabets A-Z is 65 - 90 same way for Georgian language you need to set appropriate value.


#The ASCll Table:

http://www.asciitable.com/ . 


And I think this article may help you:

http://www.c-sharpcorner.com/uploadfile/satyapriyanayak/alphabetic-paging-using-gridview-control/ .


Best Regards,

Amy Peng 



[RESOLVED] Checkboxes in my gridview being unchecked don&#39;t remove value from Dictionary


We just uncovered an odd bug in this gridview with checkboxes. (original thread:
http://forums.asp.net/post/4691898.aspx) The idea is to store the checkboxes that are checked into a dictionary that has (username, boolean) in this case the key is username, the value is boolean. As I step
through the checkbox state, I'm wanting to make it so when someone unchecks a username checkbox, it gets stripped from the checkbox dictionary. It doesn't seem to be working. I'm using the viewstate to try to keep track of which checkboxes are checked. I guess
this is what I get for trying to use GridView with paging, ugh! Here's the code:


 


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblName = ((Label)e.Row.FindControl("lblName"));
DataRowView _dv = (DataRowView)e.Row.DataItem;
UserInformation _u = new UserInformation((string)_dv.Row["USER"], false);
if (_u.Name != null)
{
lblName.Text = _u.Name;
_u = null;
}
else
{
e.Row.Visible = false;
}
String id = (String)GridView1.DataKeys[e.Row.RowIndex].Value;
if (!_checkBoxDictionary.ContainsKey(id))
{
_checkBoxDictionary.Add(id, false);
}
CheckBox checkBox = (CheckBox)e.Row.FindControl("chkSelect");
checkBox.Checked = _checkBoxDictionary[id];
}
}

protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
_checkBoxDictionary = (Dictionary)ViewState["CheckBoxDictionary"];
}

protected override object SaveViewState()
{
ViewState["CheckBoxDictionary"] = _checkBoxDictionary;
return base.SaveViewState();
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
String id = (String)GridView1.DataKeys[row.RowIndex].Value;
CheckBox checkBox = (CheckBox)row.FindControl("chkSelect");
_checkBoxDictionary[id] = checkBox.Checked;
}
}



Solved the problem with a combination of what I found there and a little of my own coding handywork. Primarily, the answer to my problem was found at

http://www.codeproject.com/Articles/202938/How-to-select-multiple-records-from-the-GridView-a


[RESOLVED] hyperlink in gridview


hi there,


my site is using a gridview including a hyperlink column (select)


this works fine if you click select, all data located in that row will be transformed to a next page at the right spot; everything ok.


But if my gridview generates a number of rows, the following hyperlinks are not working, it shows only the 'select' text


but it is not click-able. The strange thing is that it worked fine the first time i build it.


what goes wrong in here?  it can't be a big thing


kind regards


Romano


            Width="1150px" AllowPaging="True" PageSize="14"
onpageindexchanging="GV_PageIndexChanging" AllowSorting="True"
BorderColor="#109DAA" BorderStyle="Solid" BorderWidth="2px">



ShowHeader="False" SortExpression="IMAGE">

Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />
Width="60px" CssClass="GVstyle" />


Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />
CssClass="GVstyle" Wrap="True" />


Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />



Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />



Font-Underline="False" ForeColor="#109DAA" BorderColor="#109DAA"
BorderStyle="Solid" BorderWidth="2px" />


DataNavigateUrlFormatString="outputpage.aspx?IMAGE={0}&NAME={1}&CITY={2}&PROFESSION={3}&CATEGORY={4}&GENDER={5}&AGE={6}&STATES={7}&TELEPHONE={8}&EMAIL={9}&EMPLOYER={10}&YEARS={11}&EDUCATION={12}&MOTIVATION={13}&INFORMATION={14}"
Text="Select" >







Code behind


protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
DataBind();
}
}

private void BindData()
{
string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connstr);

DataSet DS = new DataSet();
DataTable members = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand SelectCommand = new SqlCommand();
SelectCommand.CommandType = CommandType.Text;

SelectCommand.CommandText = "SELECT NAME,GENDER,AGE,STATES,CITY,TELEPHONE,EMAIL,CATEGORY,PROFESSION,EMPLOYER,YEARS,EDUCATION,MOTIVATION,INFORMATION,IMAGE FROM members WHERE STATES = @STATES AND CATEGORY = @CATEGORY ";
SelectCommand.Connection = conn;

SelectCommand.Parameters.Add("@STATES",SqlDbType.VarChar).Value = DropDownList7.SelectedItem.Text;
SelectCommand.Parameters.Add("@CATEGORY",SqlDbType.VarChar).Value = DropDownList8.SelectedItem.Text;

da.SelectCommand = SelectCommand;
da.Fill(DS);
GV.DataSource = DS;
GV.DataBind();

if (GV.Rows.Count == 0)
{
errormessage.Text = "there are no members to be found, please try it again later";
}
if (GV.Rows.Count > 0)
{
errormessage.Text = "";
}

conn.Close();

}

protected void GV_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GV.PageIndex = e.NewPageIndex;
BindData();
}

protected void Button10_Click(object sender, EventArgs e)
{

BindData();
}

}



Usually, HyperLinkField not clickable because DataNavigateUrlFields has null value, check the data. Why not simply passing id value and get another values in another page based this id?

[RESOLVED] GridView disaper when paging


HI


Could someon help me with Gridview which disaper if i click on one of the  pages


My Code:


asp:GridView
ID="GridOut"
runat="server"
AutoGenerateColumns="false"
AllowPaging="true"
PageSize="20"
OnPageIndexChanging="GridPage">


<Columns>


<asp:BoundField
DataField="UserName"
HeaderText="Name"
/>


<asp:BoundField
DataField="UserAddress"
HeaderText="Address"
/> 


Columns>


asp:GridView>


protected void GetUser_Submit(object sender, EventArgs e)        


 {


<PSObject>
CollectionforGreadView= getUser.GetUserAccount(ConnectAD); //Hier i get my my collection.


            GridOut.DataSource = CollectionforGreadView;


            GridOut.DataBind();


}


 


void
GridPage(
object
sender,
GridViewPageEventArgs
e)


        {


            GridOut.PageIndex = e.NewPageIndex;


            GridOut.DataBind();  


        }


U user master page and if i press GetUser_Submitt button my GridView is filled with Data but if i press
next page it disapers...


Why...


Should i do somthing with postback....


 


Thanks for your answer.



try


void GridPage(object sender, GridViewPageEventArgs e)

{

GridOut.PageIndex = e.NewPageIndex;


}







try to update your method ,


void GridPage(object sender, GridViewPageEventArgs e)

{

GridOut.PageIndex = e.NewPageIndex;

GridOut.DataBind();

}

With following,


void GridPage(object sender, GridViewPageEventArgs e)

{

GridOut.PageIndex = e.NewPageIndex;

GridOut.DataSource = YourData;

GridOut.DataBind();

}









Thanks for your answer...


I tried but the problem is that my Colleciton "CollectionforGreadView" is not Accesible in GridPage method.


I get collection after button click event.



I made Collection public and implemented it but it is still disaper...


Please notcie that i also use masterpage.


Does it have somthing with that to do...



using masterpage doesn't matter. The basic idea is to repopulate your GridView with the updated data after you do the paging and then call DataBind().



protected void GetUser_Submit(object sender, EventArgs e)

{

CollectionforGreadView= getUser.GetUserAccount(ConnectAD); //Hier i get my my collection.

GridOut.DataSource = CollectionforGreadView;
Session("DataSource") = CollectionGreadView;

GridOut.DataBind();

}



void GridPage(object sender, GridViewPageEventArgs e)

{

GridOut.PageIndex = e.NewPageIndex;
DataSource = Session("DataSource");
GridOut.DataSource = DataSource;
GridOut.DataBind();

}

Update your code with above code..Try it and give feedback...You have to use session variable to get the datasource after postback..


Mark my post as Answer if it solve your problem..



Hi,


You can refer the sample about paging in gridview


http://www.nullskull.com/a/1645/aspnet-basics-gridview-from-database-with-paging-sorting-and-editing.aspx


And refer the similar thread:


http://forums.asp.net/t/1902480.aspx/1/10


Hope it can help you


[RESOLVED] Sorting problem in DataGrid


Hii All,


actually my problem is that I am using data grid (not gridview) in web application. The coloumns of data grid is dynamic and also set the autogeneratecoloumn="true" and also allow sortinng="true" but when I am trying to sort the coloumn
then no effect,,,,,,,


why is it so?????


Please help me ,,,,, I want to sort the colomns in the datagrid


Thanxxx in advance



hi, to do gridview sorting you need to set SortExpression in the grid's boundfields and templatefields and you need to write code in GridView_Sorting event. refer below links


http://forums.asp.net/t/1775129.aspx/1?BoundField+Can+t+be+Sorted


http://forums.asp.net/t/1887880.aspx/1?Datatable+sort+and+remove+sorting


http://forums.asp.net/t/1912069.aspx/1?How+to+sort+last+five+digits+in+Gridview



Hi,


showing some code would likely help.


As of ASP.NET 2.0 the datagrid control became rather obsolete so likely it's better to make use of a newer control if possible.


Grz, Kris.



Maybe you call binding in page_load event, place it in if(!ispostback) block



Hello All


This is the aspx code


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddUser.aspx.cs" Inherits="e_terra.Admin.AddUser" %>











   

   

    

   



   



   




       


           


       


    

        



            user updation

        



        



        





           


                





               

                   

                       

                       

                       

                       

                   

                   

                       

                       

                       

                       

                   

                   

                       

                       

                       

                       

                   

                   

                       

                       

                       

                       

                   

                   

                       

                        

                       

                       

                       

                   

                   

                       

                       

                       

                       

                   

                   

                       

                       

                       

                       

                        

                   

               


                           

                       


                           

                            

                       


                           

                       


                           

                            

                            

                       


                           

                       


                           

                            

                       


                           

                       


                           

                                onselectedindexchanged="user_role_SelectedIndexChanged"   >

                           


                            

                       


                           

                       


                           

                            

                       


                           

                       


                           

                                onselectedindexchanged="manager_desig_SelectedIndexChanged" >

                                

                           




                            

                       


                           

                       


                           

                            

                       


                           

                       


                           

                            

                           

                       


                           

                       


                           

                       


                           

                       


                           

                            

                       


                           

                       


                           

                            

                       


                           

                       


                           

                            

                       


                           

                       


                           

                            

                       


                             


                            

                       


                





           




           


           


           




           




           


                

               
                    onclick="Button1_Click" />

                

               
                    onclick="Button2_Click" />

                

               
                    onclick="Button3_Click" />

                

               

               

            


            


             

            


             

                 

                 

                   

                         BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1"


                         Width="100%" oneditcommand="DataGrid_EditCommand"

                         onpageindexchanged="DataGrid_PageIndexChanged" AllowPaging="True"

                         PageSize="3" Font-Bold="False" Font-Italic="False"

                         Font-Overline="False" Font-Size="Smaller" Font-Strikeout="False"


                         Font-Underline="False" HorizontalAlign="Left" onitemcreated="DataGrid_ItemCreated"


                        onitemdatabound="DataGrid_ItemDataBound" AllowSorting="True">

                         

                       

                            Font-Overline="False" Font-Size="Smaller" Font-Strikeout="False"


                            Font-Underline="False" />

                       

                           

                                SortExpression="SortColoumn" >

                           


                       


                       

                            Font-Size="Smaller" Font-Strikeout="False" Font-Underline="False" />

                       

                        

                       

                       

                            Font-Italic="False" Font-Overline="False" Font-Size="Smaller"


                            Font-Strikeout="False" Font-Underline="False" />

                       

                            Mode="NumericPages" />

                       

                            Font-Italic="False" Font-Overline="False" Font-Size="Smaller"


                            Font-Strikeout="False" Font-Underline="False" />

                   


                    

                 

                 

            






   


   








And the code behind is


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Web.Security;







namespace e_terra.Admin

{

    



    public partial class AddUser : System.Web.UI.Page

    {

        int iUserRole = 0;

        int iMgrDesig = 0;

        string Query;

        static string OldUserName;

        static string SortQueryForDataGrid;

        static string QueryForDataGrid;



        SqlConnection conn = new SqlConnection("Data Source=GWAY; Initial Catalog=eterrareports;User ID=sa;Password=Alstom123;Integrated Security=true");



        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                QueryForDataGrid = "select tab1.un1,tab1.ufn1,tab1.udes1,tab1.curole1,tab1.umn1,tab2.cmgrdsg2,tab1.uph1,tab1.umob1,tab1.uorg1," +

                    " tab1.ussarea1,tab1.umail1,tab1.ud1 from (SELECT u1.user_name un1,u1.user_fullname ufn1, " +

                    " u1.user_designation udes1, cl1.class_value curole1,u1.user_mgrname umn1, u1.user_phone uph1,  u1.user_mobile umob1," +

                    " u1.user_organisation uorg1,u1.user_substationarea ussarea1,  u1.user_email umail1, u1.updated_date ud1 " +

                    " FROM  user_master u1,class_MASTER cl1 where u1.USER_ROLE = cl1.class_id )tab1, " +

                    " (SELECT u2.user_name un2, cl2.class_value cmgrdsg2 " +

                    " fROM  user_master u2,class_MASTER cl2 where u2.user_mgrdesig = cl2.class_id  )tab2 "+

                    " where tab1.un1=tab2.un2 ";





                SortQueryForDataGrid = QueryForDataGrid + "order by tab1.un1";

                DisplayDataInGrid();

                RoleAndDesig();

                OldUserName = "";



            }



            //DataGrid.Attributes.Add("style", "word-break:break-all;word-wrap:normal");



            /*    user.Attributes.Add("autocomplete", "off");

            full_name.Attributes.Add("autocomplete", "off");

            desig.Attributes.Add("autocomplete", "off");

            manager.Attributes.Add("autocomplete", "off");

            phone.Attributes.Add("autocomplete", "off");

            mobile.Attributes.Add("autocomplete", "off");

            org.Attributes.Add("autocomplete", "off");

            area.Attributes.Add("autocomplete", "off");

            email_id.Attributes.Add("autocomplete", "off");

            */



            

        }



        private void RoleAndDesig()             // for populate the dropdown list

        {

            int i;



            try

            {

                conn.Open();

                Query = "select CLASS_ID,CLASS_VALUE from CLASS_MASTER where CLASS_CATEGORY='USER_ROLE'";

                SqlCommand SqlCmd = new SqlCommand(Query, conn);

                SqlDataReader SqlRead = SqlCmd.ExecuteReader();

                i = 0;

                user_role.Items.Clear();

                user_role.Items.Add("----Select User Role----");

                while (SqlRead.Read())

                {

                    user_role.Items.Add(SqlRead.GetString(1).ToString());

                    i = i + 1;

                }

                SqlRead.Close();

                SqlCmd.Dispose();

            }

            catch (Exception ex)

            {



            }

            finally

            {

                if (conn.State == ConnectionState.Open)

                {

                    conn.Close();

                }

            }





            try

            {

                conn.Open();

                Query = "select CLASS_ID,CLASS_VALUE from CLASS_MASTER where CLASS_CATEGORY='MANAGER_DESIGNATION'";

                SqlCommand SqlCmd = new SqlCommand(Query, conn);

                SqlDataReader SqlRead = SqlCmd.ExecuteReader();

                i = 0;

                manager_desig.Items.Clear();

                manager_desig.Items.Add("----Select Manager Designation-----");

                while (SqlRead.Read())

                {

                    manager_desig.Items.Add(SqlRead.GetString(1).ToString());

                    i = i + 1;

                }

                SqlRead.Close();

                SqlCmd.Dispose();

            }

            catch (Exception ex)

            {



            }

            finally

            {

                if (conn.State == ConnectionState.Open)

                {

                    conn.Close();



                }

            }



        }

        

        protected int GetClassID(string s1, string s2)

        {

            int GetClassID=0 ;



            try

            {

                conn.Open();



                Query = "Select CLASS_ID from CLASS_MASTER where CLASS_CATEGORY ='" + s1 + "' and CLASS_VALUE='" + s2 + "'";

                SqlCommand SqlCmd = new SqlCommand(Query, conn);

                SqlDataReader SqlRead = SqlCmd.ExecuteReader();





                while (SqlRead.Read())

                {

                    GetClassID = SqlRead.GetInt32(0);

                }

                SqlRead.Close();

                SqlCmd.Dispose();



            }

            catch (Exception ex)

            {

                // Label1.Text = "done";

            }

            finally

            {

                if (conn.State == ConnectionState.Open)

                {

                    conn.Close();

                }

            }



            return GetClassID;



        }



        private void DisplayDataInGrid()             // to display the data in datagrid

        {

            try

            {

                conn.Open();

                

                SqlDataAdapter SqlAdapt = new SqlDataAdapter(SortQueryForDataGrid, conn);

                DataSet dset = new DataSet();

                SqlAdapt.Fill(dset);

                dset.Dispose();

                SqlAdapt.Dispose();

                DataGrid.DataSource = dset;

                DataGrid.DataBind();

                

            }

            catch (Exception ex)

            {



            }

            finally

            {

                if (conn.State == ConnectionState.Open)

                {

                    conn.Close();

                }

            }

        }



        



        private void ClearData()            // for clear selection

        {

            user.Text = "";

            full_name.Text = "";

            password.Text = "";

            confirm.Text = "";

            desig.Text = "";

            user_role.ClearSelection();

            manager.Text = "";

            manager_desig.ClearSelection();

            phone.Text = "";

            mobile.Text = "";

            org.Text = "";

            area.Text = "";

            email_id.Text = "";

            OldUserName = "";

        }



        





        protected void DataGrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)   

        {

            DataGrid.CurrentPageIndex = e.NewPageIndex;

            DisplayDataInGrid();

        }



        protected void DataGrid_EditCommand(object source, DataGridCommandEventArgs e)   // for editing the gridview row

        {

            ClearData();



            user.Text = e.Item.Cells[1].Text;

            OldUserName=e.Item.Cells[1].Text.Trim();



            if (e.Item.Cells[2].Text.ToUpper().Trim() != " ")

                full_name.Text = e.Item.Cells[2].Text;



            if (e.Item.Cells[3].Text.ToUpper().Trim() != " ")

                desig.Text = e.Item.Cells[3].Text;



            user_role.ClearSelection();

            user_role.SelectedItem.Text = e.Item.Cells[4].Text.Trim();



            if (e.Item.Cells[5].Text.ToUpper().Trim()!=" ")

                manager.Text=e.Item.Cells[5].Text;



            manager_desig.ClearSelection();

            manager_desig.SelectedItem.Text = e.Item.Cells[6].Text.Trim();



            if (e.Item.Cells[7].Text.ToUpper().Trim() != " ")

                phone.Text = e.Item.Cells[7].Text;



            if (e.Item.Cells[8].Text.ToUpper().Trim() != " ")

                mobile.Text = e.Item.Cells[8].Text;



            if (e.Item.Cells[9].Text.ToUpper().Trim() != " ")

                org.Text = e.Item.Cells[9].Text;



            if (e.Item.Cells[10].Text.ToUpper().Trim() != " ")

                area.Text = e.Item.Cells[10].Text;



            if (e.Item.Cells[11].Text.ToUpper().Trim() != " ")

                email_id.Text = e.Item.Cells[11].Text;



            

        }



        protected void user_role_SelectedIndexChanged(object sender, EventArgs e)    // to get the class Id of the dropdown list

        {

            try

            {

                conn.Open();



                Query = "Select CLASS_ID from CLASS_MASTER where CLASS_CATEGORY ='USER_ROLE' and CLASS_VALUE='" + user_role.SelectedItem.Text.ToString() + "'";

                SqlCommand SqlCmd = new SqlCommand(Query,conn);

                SqlDataReader SqlRead = SqlCmd.ExecuteReader();



                while (SqlRead.Read())

                {

                    iUserRole = SqlRead.GetInt32(0);    

                }

                SqlRead.Close();

                SqlCmd.Dispose();

            }

            catch (Exception ex)

            {



            }

            finally

            {

                if (conn.State == ConnectionState.Open)

                {

                    conn.Close();

                }

            }



        }



        protected void manager_desig_SelectedIndexChanged(object sender, EventArgs e)   // to get the class Id of the dropdown list

        {

            try

            {

                conn.Open();



                Query = "Select CLASS_ID from CLASS_MASTER where CLASS_CATEGORY ='MANAGER_DESIGNATION' and CLASS_VALUE='" + manager_desig.SelectedItem.Text.ToString() + "'";

                SqlCommand SqlCmd = new SqlCommand(Query, conn);

                SqlDataReader SqlRead = SqlCmd.ExecuteReader();



                while (SqlRead.Read())

                {

                    iMgrDesig = SqlRead.GetInt32(0);

                }

                SqlRead.Close();

                SqlCmd.Dispose();

            }

            catch (Exception ex)

            {



            }

            finally

            {

                if (conn.State == ConnectionState.Open)

                {

                    conn.Close();

                }

            }

        }



        protected void Button1_Click(object sender, EventArgs e)        // to save the user details

        {

            int RecFound = 0;

            



            if (iUserRole == 0 || iMgrDesig == 0)

            {

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('User Role or Manager Designation not selected');", true);

            }

            else

            {

                string strDate = DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt");



                if (strDate.Substring((strDate.Length - 2), 2) == "AM")

                    strDate = strDate.Replace("AM", "A.M.");

                else if (strDate.Substring((strDate.Length - 2), 2) == "PM")

                    strDate = strDate.Replace("PM", "P.M.");





                try

                {

                    conn.Open();

                    Query = "select count(user_name) from user_master where user_name='" + user.Text.ToString().Trim().ToUpper() + "'";

                    SqlCommand SqlCmd = new SqlCommand(Query, conn);

                    SqlDataReader SqlRead = SqlCmd.ExecuteReader();

                    while (SqlRead.Read())

                    {

                        RecFound = SqlRead.GetInt32(0);

                    }

                    SqlRead.Close();

                    SqlCmd.Dispose();



                }

                catch (Exception ex)

                {



                }

                finally

                {

                    if (conn.State == ConnectionState.Open)

                    {

                        conn.Close();

                    }

                }



                if (RecFound == 0)

                {

                    try

                    {

                        conn.Open();



                        Query = "Insert into User_Master(USER_NAME,USER_PASSWORD,USER_FULLNAME,USER_DESIGNATION," +

                                " USER_ROLE,USER_MGRDESIG,USER_MGRNAME,USER_PHONE,USER_MOBILE,USER_ORGANISATION," +

                                " USER_SUBSTATIONAREA,USER_EMAIL,Updated_Date) values('" +

                                user.Text.ToString().Trim().ToUpper() + "','" + password.Text.ToString().Trim() + "','" +

                                full_name.Text.ToString().Trim().ToUpper() + "','" + desig.Text.ToString().Trim().ToUpper() + "'," +

                                iUserRole + "," + iMgrDesig + ",'" + manager.Text.ToString().Trim().ToUpper() + "','" + phone.Text.ToString().Trim() + "','" +

                                mobile.Text.ToString().Trim() + "','" + org.Text.ToString().Trim().ToUpper() + "','" +

                                area.Text.ToString().Trim().ToUpper() + "','" +

                                email_id.Text.ToString().Trim() + "','" + DateTime.Now + "')";



                        SqlCommand SqlCmd = new SqlCommand(Query, conn);

                        SqlCmd.ExecuteNonQuery();

                        SqlCmd.Dispose();

                        ClearData();

                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Record Added Succesfully');", true);

                        DataGrid.DataBind();

                    }

                    catch (Exception ex)

                    {

                    }

                    finally

                    {

                        if (conn.State == ConnectionState.Open)

                        {

                            conn.Close();

                        }

                    }

                }



                else

                {

                    ClearData();

                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Record Already Exists');", true);

                }





                DisplayDataInGrid();



            }

        }



        protected void Button2_Click(object sender, EventArgs e)

        {

            if (OldUserName.Trim().Length == 0)

            {

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Record Not Found for updation');", true);

            }

            else

            {



                int RecFound = 0;

                int UserId = 0;

                int MgrId = 0;



                UserId = GetClassID("USER_ROLE", user_role.SelectedItem.ToString());

                MgrId =  GetClassID("MANAGER_DESIGNATION", manager_desig.SelectedItem.ToString());



                if (UserId == 0 || MgrId == 0)

                {

                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('User Role or Manager Designation not selected');", true);

                }

                else

                {

                    string strDate = DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt");

                    if (strDate.Substring((strDate.Length - 2), 2) == "AM")

                        strDate = strDate.Replace("AM", "A.M.");

                    else if (strDate.Substring((strDate.Length - 2), 2) == "PM")

                        strDate = strDate.Replace("PM", "P.M.");



                    // to check ehethere user already exists



                    int ChangeName = 0;



                    if (OldUserName == user.Text.ToString().Trim().ToUpper())

                    {

                        Query = "select count(user_name) from user_master where user_name='" + OldUserName + "'";

                        ChangeName = 0;

                    }

                    else

                    {

                        Query = "select count(user_name) from user_master where user_name='" + OldUserName + "'";

                        ChangeName = 1;

                    }



                    try

                    {

                        conn.Open();

                        SqlCommand SqlCmd = new SqlCommand(Query, conn);

                        SqlDataReader SqlRead = SqlCmd.ExecuteReader();

                        while (SqlRead.Read())

                        {

                            RecFound = SqlRead.GetInt32(0);

                        }

                        SqlRead.Close();

                        SqlCmd.Dispose();

                    }

                    catch (Exception ex)

                    {

                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Error');", true);

                    }

                    finally

                    {

                        if (conn.State == ConnectionState.Open)

                        {

                            conn.Close();

                        }

                    }



                    if (ChangeName == 0)

                    {

                        if (RecFound == 1)

                        {

                            try

                            {

                                conn.Open();



                                Query = "update user_master set" +

                                    "USER_PASSWORD='" + password.Text.ToString().Trim() + "'," +

                                    "USER_FULLNAME='" + full_name.Text.ToString().Trim().ToUpper() + "'," +

                                    "USER_DESIGNATION='" + desig.Text.ToString().Trim().ToUpper() + "'," +

                                    "USER_ROLE=" + UserId + "," +

                                    "USER_MGRDESIG=" + MgrId + "," +

                                    "USER_MGRNAME='" + manager.Text.ToString().Trim().ToUpper() + "'," +

                                    "USER_PHONE='" + phone.Text.ToString().Trim() + "'," +

                                    "USER_MOBILE='" + mobile.Text.ToString().Trim() + "'," +

                                    "USER_ORGANISATION='" + org.Text.ToString().Trim().ToUpper() + "'," +

                                    "USER_EMAIL='" + email_id.Text.ToString().Trim()+ "'," +

                                    "Updated_Date='" + DateTime.Now + "'where user_name='" + user.Text.ToString().Trim().ToUpper() + "'";



                                SqlCommand SqlCmd = new SqlCommand(Query, conn);

                                SqlCmd.ExecuteNonQuery();

                                SqlCmd.Dispose();

                                ClearData();

                                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Record Updated Succesfully ');", true);

                                DataGrid.DataBind();

                            }

                            catch (Exception ex)

                            {



                            }

                            finally

                            {

                                if (conn.State == ConnectionState.Open)

                                {

                                    conn.Close();

                                }

                            }

                        }



                        else

                        {

                            ClearData();

                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Record not found for updation');", true);

                        }

                    }



                    // change name



                    if (ChangeName == 1)

                    {

                        if (RecFound == 1)

                        {

                            try

                            {

                                conn.Open();



                                Query = "update user_master set " +

                                    "user_name = '" + user.Text.ToString().Trim().ToUpper() + "'," +

                                    "user_password='" + password.Text.ToString().Trim().ToUpper() + "'," +

                                    "user_fullname='" + full_name.Text.ToString().Trim().ToUpper() + "'," +

                                    "user_designation='" + desig.Text.ToString().Trim().ToUpper() + "'," +

                                    "user_role=" + UserId + "," +

                                    "user_mgrdesig=" + MgrId + "," +

                                    "user_mgrname='" + manager.Text.ToString().Trim().ToUpper() + "'," +

                                    "user_phone='" + phone.Text.ToString().Trim().ToUpper() + "'," +

                                    "user_mobile='" + mobile.Text.ToString().Trim().ToUpper() + "'," +

                                    "user_organisation='" + org.Text.ToString().Trim().ToUpper() + "'," +

                                    "user_substationarea='" + area.Text.ToString().Trim().ToUpper() + "'," +

                                    "user_email='" + email_id.Text.ToString().Trim() + "'," +

                                    "updated_date='" + DateTime.Now + "'where user_name='" + OldUserName + "'";



                                SqlCommand SqlCmd = new SqlCommand(Query, conn);

                                SqlCmd.ExecuteNonQuery();

                                SqlCmd.Dispose();

                                ClearData();

                                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Record Updated Succesfully');", true);

                                DataGrid.DataBind();

                                RoleAndDesig();

                            }

                            catch (Exception ex)

                            {

                            }

                            finally

                            {

                                if (conn.State == ConnectionState.Open)

                                {

                                    conn.Close();

                                }

                            }

                        }



                        else

                        {

                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('User Name already exists');", true);

                        }

                    }



                    DisplayDataInGrid();    

                }

                

            }

        }



        protected void Button3_Click(object sender, EventArgs e)

        {

            ClearData();

        }



        protected void DataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)

        {

            if (e.Item.ItemType == ListItemType.Header)

            {

                e.Item.Cells[1].Text = "User ID";

                e.Item.Cells[2].Text = "User Name";

                e.Item.Cells[3].Text = "Designation";

                e.Item.Cells[4].Text = "Role";

                e.Item.Cells[5].Text = "Manager's Name";

                e.Item.Cells[6].Text = "Manager's Designation";

                e.Item.Cells[7].Text = "Phone";

                e.Item.Cells[8].Text = "Mobile";

                e.Item.Cells[9].Text = "Organization";

                e.Item.Cells[10].Text = "Substation Area";

                e.Item.Cells[11].Text = "Email ID";

                e.Item.Cells[12].Text = "Updated Date";

            }

        }



        protected void DataGrid_ItemCreated(object sender, DataGridItemEventArgs e)

        {

            if (e.Item.ItemType == ListItemType.Header)

            {

                e.Item.Cells[1].Text = "User ID";

                e.Item.Cells[2].Text = "User Name";

                e.Item.Cells[3].Text = "Designation";

                e.Item.Cells[4].Text = "Role";

                e.Item.Cells[5].Text = "Manager's Name";

                e.Item.Cells[6].Text = "Manager's Designation";

                e.Item.Cells[7].Text = "Phone";

                e.Item.Cells[8].Text = "Mobile";

                e.Item.Cells[9].Text = "Organization";

                e.Item.Cells[10].Text = "Substation Area";

                e.Item.Cells[11].Text = "Email ID";

                e.Item.Cells[12].Text = "Updated Date";

            }

        }



        protected void DataGrid_SortCommand(object source, DataGridSortCommandEventArgs e)

        {

            SortQueryForDataGrid = QueryForDataGrid + "order by" + e.SortExpression;

            DisplayDataInGrid();

        }





    }

}






Hi,


Suggest that you should store the sortexpression into viewstate. For detailed information, you can refer here


http://www.codeproject.com/Articles/67520/GridView-Paging-and-Sorting


http://stackoverflow.com/questions/702600/sorting-and-paging-with-gridview-asp-net


Hope it can help you