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

2014年7月13日 星期日

[RESOLVED] how to search data from gridview if i have bind it using sqldatasourse


hi


i am new in asp.net


i have a problem to search data from gridview


i have bind gridview using article:http://msdn.microsoft.com/en-us/library/ms972948.aspx


now i want to search record from that


i have textbox to enter search term and serch button to search


note: i want to use like operator to search the records


please help me


thanks in advance





Vjitendra



i have textbox to enter search term and serch button to search


note: i want to use like operator to search the records





Check this link,this is the exact way what you want


http://www.aspdotnet-suresh.com/2011/12/search-records-in-gridview-and.html


[RESOLVED] Error Help Requested


I'm getting an error that says "Unrecognised tag prefix or device filter 'rsweb'.


I'm following along on a tutorial that is helping me display a report in a web form.  Can someone please look at this markup and let me know what I'm doing wrong?


 


    


       


      Filter by: Category :        


       


 and Supplier :        


    


 


    



 



you need to register reportview assembly to be able to use reportviewr control


add this at top of aspx page (after page directive)


<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

or u can add assembly in web.config


note that, the version number could be 8.0/9.0/10.0 etc. based on what reportviewer assembly is present in u r machine


hope this helps...



Thank you very much.


[RESOLVED] Line up drop down menu items?


Hi,


Using the code below I am populating a drop down menu but the text does not line up. Is there a way so that when the drop down loads that the City part is all in line? Currently the city part can be more to left or more to the right depending on the length
of the column before it? Thanks!


While reader.Read
customers.Add(reader("Provider Last Name (Legal Name)").ToString + ", " + reader("Provider First Name").ToString + " " + reader("Provider Business Mailing Address City Name").ToString + ", " + reader("Provider Business Mailing Address State Name").ToString + " " + reader("Provider Business Mailing Address Postal Code").ToString)

End While



I've created some similar functionality in the past for aligning items within Dropdowns that leverages the empty character (ALT+255) to create spaces within drop-downs that are recognized within


It uses some of the available padding within the String formatting function to allocate exactly how many characters you want to use for a specific field and then has an additional function to replace those spaces with the "invisible character" : 


string FormatForDropDown(string s, int length)
{
//Builds a string
StringBuilder sb = new StringBuilder();
//Iterates through and replaces the empty values with the empty character (not a space)
for (int i = 0; i < length; i++)
{
sb.Append((i < s.Length) ? s[i].ToString() : " ");
}
//Outputs the string
return sb.ToString();
}

and as far as actually adding the actual entry, it should be used as such : 


//Example of the item you would add to your Drop-down list
String.Format("{0,24} | {1,12} | {2,24}", FormatForDropDown(valueA, 24), FormatForDropDown(valueB, 12), FormatForDropDown(valueC, 24));

(Warning : This is old code)







Since you are using Visual Basic, it may look something like this : 


Public Function FormatForDropDown(ByVal s As String, ByVal length As Integer) As String
Dim sb = New StringBuilder()
For i As Integer = 0 To length
sb.Append(If(i < s.Length, s(i).ToString(), " "))
Next
Return sb.ToString()
End Function

and


'String to Add'
Dim entry = String.Format("{0,24} | {1,24} | {2,24} | {3,24} | {4, 24}",reader("Provider Last Name (Legal Name)").ToString(),reader("Provider Business Mailing Address City Name").ToString(), reader("Provider First Name").ToString(),reader("Provider Business Mailing Address State Name").ToString(), reader("Provider Business Mailing Address Postal Code").ToString()
'Add the entry'
customers.Add(entry)

Alternatively, you could simply replace the strings of spaces that you are using with the invisible character " " as mentioned : 


While reader.Read
customers.Add(reader("Provider Last Name (Legal Name)").ToString() + ", " + reader("Provider First Name").ToString + "          " + reader("Provider Business Mailing Address City Name").ToString() + ", " + reader("Provider Business Mailing Address State Name").ToString() + "  " + reader("Provider Business Mailing Address Postal Code").ToString())
End While

I attempted to replace them in the code above however it may not have worked properly. It's just important to note that all of the spaces that you see above within your strings are not actual spaces but the invisible character (ALT+255).







Thanks, this seems to be close to what i need, proglem is some of the last names have a "-" so it throws off the alignment. Thanks for your help with this. Maybe can it be a set width so its like an excel sheet where its just like a straight line between
with a set length?


               JOHNSON |                    AJITA |                     BEAR |                       DE |                197013036


               JOHNSON-Smith |                    AJITA |                     BEAR |                       DE |                197013036


 


[RESOLVED] GridView column is hidden when export to excel exlcude the hidden column


I have a gridview, some of column is hidden but when i export to excel, in excel it still show the hidden column. May i know how to do it??


below is my sample script in App_Code:


public class GridViewExportUtil

{



    public static void Export(string fileName, GridView gv)

    {

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.ClearContent();

        HttpContext.Current.Response.ClearHeaders();

        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));



         using (StringWriter sw = new StringWriter())

        {

            using (HtmlTextWriter htw = new HtmlTextWriter(sw))

            {

                Table table = new Table();




                if (gv.HeaderRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);

                    table.Rows.Add(gv.HeaderRow);

                }



                foreach (GridViewRow row in gv.Rows)

                {

                    GridViewExportUtil.PrepareControlForExport(row);

                    table.Rows.Add(row);

                    

                }



                if (gv.FooterRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);

                    table.Rows.Add(gv.FooterRow);

                }



                table.RenderControl(htw);



                HttpContext.Current.Response.Write(sw.ToString());

                HttpContext.Current.Response.Flush();

                HttpContext.Current.Response.Close();

                HttpContext.Current.Response.End();

            }

        }

    }



    private static void PrepareControlForExport(Control control)

    {

        for (int i = 0; i < control.Controls.Count; i++)

        {

            Control current = control.Controls[i];

            if (current is LinkButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));

            }

            else if (current is ImageButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));

            }

            else if (current is HyperLink)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));

            }

            else if (current is DropDownList)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));

            }

            else if (current is CheckBox)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));

            }

            else if (current.Visible == false)

            {

                control.Controls.Remove(current);

            }

            if (current.HasControls())

            {

                GridViewExportUtil.PrepareControlForExport(current);

            }

        }

    }



Maybe you can do like this


GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;









oned_gk



Maybe you can do like this
GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;




Thank for your information. I have try to add in the below code, but the problem still same....any idea??

                for (int i = gv.Columns.Count - 1; i >= 0; i--)

                {

                    if (gv.Columns[i].Visible == false)

                    {

                        gv.HeaderRow.Cells[i].Visible = false;

                        gv.FooterRow.Cells[i].Visible = false;

                    }

                    gv.Columns[i].Visible = false;

                }



Hi lansishao,


I have checked your code and to me, the method PrepareControlForExport(Control control) needs some refinement, actually when u replace different controls like link-buttons, dropdowns etc with LiteralControl controls, there you should check the visibility
of the actual control, if actual control is visible then you should replace it with Literal otherwise no need to add it. Hopefully you got my point,


else if (current is CheckBox && current.Visible)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}







Thanks 



Thank for your information. But actually i no so understand what you mean. Can you provide me some sample of code? thank you.



here it is,code id Bold and and under-lined


else if (current is CheckBox && current.Visible) // visibility check
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}



Thank you...but after i try ur method add on the code, after export the data to excel, those hidden column still show....
Cry



can you share the ASPX page code, where you are hiding the grid columns, like grid item template and specially the hidden column template.


thanks



this is sample as below:




        EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="Vertical"             

        style="font-family: 'Century Gothic'; font-size: small" Width="98%" ShowFooter="True"

        OnPreRender = "gv_PreRender" OnRowDataBound = "gv_RowDataBound">

   

   

                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


   



change your hidden item template as follow,




ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Jan") %>'>


ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Feb") %>'>










thanks for you...i have set the label to visible and the problem solved..


because it have many page...may i know any best way to amend the code what i post before?



it is good to know that your problem solved, please mark the thread as answered if it helps you Innocent


Secondly, in your code you are checking at control Level that if it is visible or not, your code line


if(control.visible==false)

so you have to apply the visible attribute to every control in every grid in every page, other wise chagne the code to export data, that change of code, may introduce other problems :) 




[RESOLVED] Solution for &quot;Format of the initialization string does not conform to specification starting at index 0.&quot;?


not sure from when, I started get error: Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0. I am using Microsoft .NET Framework Version:2.0.40607.42; ASP.NET Version:2.0.40607.42
and sql 2005 beta, the connectionstring in web.config like this: It happens on string connString = ConfigurationSettings.ConnectionStrings["dbbase"].ToString(); SqlConnection conn = new SqlConnection(connString); -- this line It seems a few people had this
problem, but I could not find an answer. On microsoft site, there is a fix for asp.net 1.1 and it says this happens when there is ' or " in connection string, but both not in my case. please help/ Thanks!

Any luck with this?  I've got the same problem.

Anyone find a solution to this?? I have the same problem. I'm fairly sure my connection string in my config file is correct so it has to be a coding error.


protected void Button1_Click(object sender,
EventArgs e)

{


 


string sql = DropDownList1.SelectedValue;if (!String.IsNullOrEmpty(sql))

{


String EC = "EsteeConnection";

 


using (SqlConnection Connection =
new SqlConnection(EC))

{


using (SqlCommand Command =
new SqlCommand(sql, Connection))

{


Connection.Open();


SqlDataReader reader = Command.ExecuteReader(CommandBehavior.CloseConnection);

GridView1.DataSource = reader;


GridView1.DataBind();


}


}


}


}


Anyone see a mistake in this??




Anyone find a solution to this?? I have the same problem. I'm fairly sure my connection string in my config file is correct so it has to be a coding error.


protected void Button1_Click(object sender,
EventArgs e)

{


 


string sql = DropDownList1.SelectedValue;if (!String.IsNullOrEmpty(sql))

{


String EC = "EsteeConnection";

 


using (SqlConnection Connection =
new SqlConnection(EC))

{


using (SqlCommand Command =
new SqlCommand(sql, Connection))

{


Connection.Open();


SqlDataReader reader = Command.ExecuteReader(CommandBehavior.CloseConnection);

GridView1.DataSource = reader;


GridView1.DataBind();


}


}


}


}


Anyone see a mistake in this??




http://www.velocityreviews.com/forums/t87146-simple-dbproblem.html


i found the solution to my problem here ...  the new connection string had to be called diffeerently.


Hope this helps other people.



Actually never mind that doesn't seem to be working the way i want .. anybody got any ideas??



I would suggest you re-check your connection string. Refer
http://www.connectionstrings.com/
 



you have to set up the SQL connection settings for this drag and drop SQL data source and set it up as per your knowledge.



hope that will resolve the error.


[RESOLVED] DropDownList allow 1 to 40


how do i create a drop list from 1 to 40... without out writing 40 plus lines...


see example below which allows the user to select 1 to 10, but if this needs to be extended to 40 then there will be 40 plus lines!!!





































Try this:


for (int i = 0; i <= 40; i++)
{
dropDownList.Add(new ListItem(i,i); //the first i is for text, second for value
}




You could create a collection that would holds the numbers 1 to 40 and then bind them to your DropDownList. In this case you would need to use code-behind to populate your List.


[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] how to search data from gridview if i have bind it using sqldatasourse


hi


i am new in asp.net


i have a problem to search data from gridview


i have bind gridview using article:http://msdn.microsoft.com/en-us/library/ms972948.aspx


now i want to search record from that


i have textbox to enter search term and serch button to search


note: i want to use like operator to search the records


please help me


thanks in advance





Vjitendra



i have textbox to enter search term and serch button to search


note: i want to use like operator to search the records





Check this link,this is the exact way what you want


http://www.aspdotnet-suresh.com/2011/12/search-records-in-gridview-and.html


[RESOLVED] Error Help Requested


I'm getting an error that says "Unrecognised tag prefix or device filter 'rsweb'.


I'm following along on a tutorial that is helping me display a report in a web form.  Can someone please look at this markup and let me know what I'm doing wrong?


 


    


       


      Filter by: Category :        


       


 and Supplier :        


    


 


    



 



you need to register reportview assembly to be able to use reportviewr control


add this at top of aspx page (after page directive)


<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

or u can add assembly in web.config


note that, the version number could be 8.0/9.0/10.0 etc. based on what reportviewer assembly is present in u r machine


hope this helps...



Thank you very much.


[RESOLVED] Line up drop down menu items?


Hi,


Using the code below I am populating a drop down menu but the text does not line up. Is there a way so that when the drop down loads that the City part is all in line? Currently the city part can be more to left or more to the right depending on the length
of the column before it? Thanks!


While reader.Read
customers.Add(reader("Provider Last Name (Legal Name)").ToString + ", " + reader("Provider First Name").ToString + " " + reader("Provider Business Mailing Address City Name").ToString + ", " + reader("Provider Business Mailing Address State Name").ToString + " " + reader("Provider Business Mailing Address Postal Code").ToString)

End While



I've created some similar functionality in the past for aligning items within Dropdowns that leverages the empty character (ALT+255) to create spaces within drop-downs that are recognized within


It uses some of the available padding within the String formatting function to allocate exactly how many characters you want to use for a specific field and then has an additional function to replace those spaces with the "invisible character" : 


string FormatForDropDown(string s, int length)
{
//Builds a string
StringBuilder sb = new StringBuilder();
//Iterates through and replaces the empty values with the empty character (not a space)
for (int i = 0; i < length; i++)
{
sb.Append((i < s.Length) ? s[i].ToString() : " ");
}
//Outputs the string
return sb.ToString();
}

and as far as actually adding the actual entry, it should be used as such : 


//Example of the item you would add to your Drop-down list
String.Format("{0,24} | {1,12} | {2,24}", FormatForDropDown(valueA, 24), FormatForDropDown(valueB, 12), FormatForDropDown(valueC, 24));

(Warning : This is old code)







Since you are using Visual Basic, it may look something like this : 


Public Function FormatForDropDown(ByVal s As String, ByVal length As Integer) As String
Dim sb = New StringBuilder()
For i As Integer = 0 To length
sb.Append(If(i < s.Length, s(i).ToString(), " "))
Next
Return sb.ToString()
End Function

and


'String to Add'
Dim entry = String.Format("{0,24} | {1,24} | {2,24} | {3,24} | {4, 24}",reader("Provider Last Name (Legal Name)").ToString(),reader("Provider Business Mailing Address City Name").ToString(), reader("Provider First Name").ToString(),reader("Provider Business Mailing Address State Name").ToString(), reader("Provider Business Mailing Address Postal Code").ToString()
'Add the entry'
customers.Add(entry)

Alternatively, you could simply replace the strings of spaces that you are using with the invisible character " " as mentioned : 


While reader.Read
customers.Add(reader("Provider Last Name (Legal Name)").ToString() + ", " + reader("Provider First Name").ToString + "          " + reader("Provider Business Mailing Address City Name").ToString() + ", " + reader("Provider Business Mailing Address State Name").ToString() + "  " + reader("Provider Business Mailing Address Postal Code").ToString())
End While

I attempted to replace them in the code above however it may not have worked properly. It's just important to note that all of the spaces that you see above within your strings are not actual spaces but the invisible character (ALT+255).







Thanks, this seems to be close to what i need, proglem is some of the last names have a "-" so it throws off the alignment. Thanks for your help with this. Maybe can it be a set width so its like an excel sheet where its just like a straight line between
with a set length?


               JOHNSON |                    AJITA |                     BEAR |                       DE |                197013036


               JOHNSON-Smith |                    AJITA |                     BEAR |                       DE |                197013036


 


[RESOLVED] GridView column is hidden when export to excel exlcude the hidden column


I have a gridview, some of column is hidden but when i export to excel, in excel it still show the hidden column. May i know how to do it??


below is my sample script in App_Code:


public class GridViewExportUtil

{



    public static void Export(string fileName, GridView gv)

    {

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.ClearContent();

        HttpContext.Current.Response.ClearHeaders();

        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));



         using (StringWriter sw = new StringWriter())

        {

            using (HtmlTextWriter htw = new HtmlTextWriter(sw))

            {

                Table table = new Table();




                if (gv.HeaderRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);

                    table.Rows.Add(gv.HeaderRow);

                }



                foreach (GridViewRow row in gv.Rows)

                {

                    GridViewExportUtil.PrepareControlForExport(row);

                    table.Rows.Add(row);

                    

                }



                if (gv.FooterRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);

                    table.Rows.Add(gv.FooterRow);

                }



                table.RenderControl(htw);



                HttpContext.Current.Response.Write(sw.ToString());

                HttpContext.Current.Response.Flush();

                HttpContext.Current.Response.Close();

                HttpContext.Current.Response.End();

            }

        }

    }



    private static void PrepareControlForExport(Control control)

    {

        for (int i = 0; i < control.Controls.Count; i++)

        {

            Control current = control.Controls[i];

            if (current is LinkButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));

            }

            else if (current is ImageButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));

            }

            else if (current is HyperLink)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));

            }

            else if (current is DropDownList)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));

            }

            else if (current is CheckBox)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));

            }

            else if (current.Visible == false)

            {

                control.Controls.Remove(current);

            }

            if (current.HasControls())

            {

                GridViewExportUtil.PrepareControlForExport(current);

            }

        }

    }



Maybe you can do like this


GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;









oned_gk



Maybe you can do like this
GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;




Thank for your information. I have try to add in the below code, but the problem still same....any idea??

                for (int i = gv.Columns.Count - 1; i >= 0; i--)

                {

                    if (gv.Columns[i].Visible == false)

                    {

                        gv.HeaderRow.Cells[i].Visible = false;

                        gv.FooterRow.Cells[i].Visible = false;

                    }

                    gv.Columns[i].Visible = false;

                }



Hi lansishao,


I have checked your code and to me, the method PrepareControlForExport(Control control) needs some refinement, actually when u replace different controls like link-buttons, dropdowns etc with LiteralControl controls, there you should check the visibility
of the actual control, if actual control is visible then you should replace it with Literal otherwise no need to add it. Hopefully you got my point,


else if (current is CheckBox && current.Visible)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}







Thanks 



Thank for your information. But actually i no so understand what you mean. Can you provide me some sample of code? thank you.



here it is,code id Bold and and under-lined


else if (current is CheckBox && current.Visible) // visibility check
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}



Thank you...but after i try ur method add on the code, after export the data to excel, those hidden column still show....
Cry



can you share the ASPX page code, where you are hiding the grid columns, like grid item template and specially the hidden column template.


thanks



this is sample as below:




        EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="Vertical"             

        style="font-family: 'Century Gothic'; font-size: small" Width="98%" ShowFooter="True"

        OnPreRender = "gv_PreRender" OnRowDataBound = "gv_RowDataBound">

   

   

                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


   



change your hidden item template as follow,




ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Jan") %>'>


ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Feb") %>'>










thanks for you...i have set the label to visible and the problem solved..


because it have many page...may i know any best way to amend the code what i post before?



it is good to know that your problem solved, please mark the thread as answered if it helps you Innocent


Secondly, in your code you are checking at control Level that if it is visible or not, your code line


if(control.visible==false)

so you have to apply the visible attribute to every control in every grid in every page, other wise chagne the code to export data, that change of code, may introduce other problems :) 




[RESOLVED] Solution for &quot;Format of the initialization string does not conform to specification starting at index 0.&quot;?


not sure from when, I started get error: Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0. I am using Microsoft .NET Framework Version:2.0.40607.42; ASP.NET Version:2.0.40607.42
and sql 2005 beta, the connectionstring in web.config like this: It happens on string connString = ConfigurationSettings.ConnectionStrings["dbbase"].ToString(); SqlConnection conn = new SqlConnection(connString); -- this line It seems a few people had this
problem, but I could not find an answer. On microsoft site, there is a fix for asp.net 1.1 and it says this happens when there is ' or " in connection string, but both not in my case. please help/ Thanks!

Any luck with this?  I've got the same problem.

Anyone find a solution to this?? I have the same problem. I'm fairly sure my connection string in my config file is correct so it has to be a coding error.


protected void Button1_Click(object sender,
EventArgs e)

{


 


string sql = DropDownList1.SelectedValue;if (!String.IsNullOrEmpty(sql))

{


String EC = "EsteeConnection";

 


using (SqlConnection Connection =
new SqlConnection(EC))

{


using (SqlCommand Command =
new SqlCommand(sql, Connection))

{


Connection.Open();


SqlDataReader reader = Command.ExecuteReader(CommandBehavior.CloseConnection);

GridView1.DataSource = reader;


GridView1.DataBind();


}


}


}


}


Anyone see a mistake in this??




Anyone find a solution to this?? I have the same problem. I'm fairly sure my connection string in my config file is correct so it has to be a coding error.


protected void Button1_Click(object sender,
EventArgs e)

{


 


string sql = DropDownList1.SelectedValue;if (!String.IsNullOrEmpty(sql))

{


String EC = "EsteeConnection";

 


using (SqlConnection Connection =
new SqlConnection(EC))

{


using (SqlCommand Command =
new SqlCommand(sql, Connection))

{


Connection.Open();


SqlDataReader reader = Command.ExecuteReader(CommandBehavior.CloseConnection);

GridView1.DataSource = reader;


GridView1.DataBind();


}


}


}


}


Anyone see a mistake in this??




http://www.velocityreviews.com/forums/t87146-simple-dbproblem.html


i found the solution to my problem here ...  the new connection string had to be called diffeerently.


Hope this helps other people.



Actually never mind that doesn't seem to be working the way i want .. anybody got any ideas??



I would suggest you re-check your connection string. Refer
http://www.connectionstrings.com/
 



you have to set up the SQL connection settings for this drag and drop SQL data source and set it up as per your knowledge.



hope that will resolve the error.


[RESOLVED] DropDownList allow 1 to 40


how do i create a drop list from 1 to 40... without out writing 40 plus lines...


see example below which allows the user to select 1 to 10, but if this needs to be extended to 40 then there will be 40 plus lines!!!





































Try this:


for (int i = 0; i <= 40; i++)
{
dropDownList.Add(new ListItem(i,i); //the first i is for text, second for value
}




You could create a collection that would holds the numbers 1 to 40 and then bind them to your DropDownList. In this case you would need to use code-behind to populate your List.


[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] 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