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

2014年7月13日 星期日

[RESOLVED] Exporting datalist and gridview to excel


Hello Experts,


I am having one datalist and gridview within datalist control. I need to export both of them as report in excel sheet. Like below


sr.  Class  CreatedDate ModifiedDate


1     Class1   25/5/2013   25/5/2013


Students


Sr.  Name Address Bdate


1    Abc    test add  25/5/1990


2    DEF   test add 2  25/3/1991


sr.  Class  CreatedDate ModifiedDate


2     Class2   25/6/2013   25/6/2013


Students


Sr.  Name Address Bdate


1    Abc2    test add22  25/5/1990


2    DEF2   test add 22  25/3/1991


and so on.....


Here the class display is datalist and student display is gridview.


Please suggest how to achive that?


Thank you.




Refer bellow url


http://www.aspsnippets.com/Articles/Export-GridView-To-WordExcelPDFCSV-in-ASP.Net.aspx



Hi,


Please try to refer to the following code about export data to excel (use the gridview as an example):


protected void fillGrid()
{
string str = "SELECT [UNo], [EmpName], [Age],
convert(char,[dob],103) dob FROM [tbl_EmpDetails]";

myConnection = new SqlConnection(conn);
myConnection.Open();
myCommand = new SqlCommand(str, myConnection);
SqlDataAdapter mySQLDataAdapter;
myDataSet = new DataTable();
mySQLDataAdapter = new SqlDataAdapter(myCommand);
mySQLDataAdapter.Fill(myDataSet);
GridView1.DataSource = myDataSet;
GridView1.DataBind();
ViewState["dtList"] = myDataSet;
}

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillGrid();
}
}

Now, after binding a Gridview, data is ready to get exported to an Excel file. Click on a button named Export to Excel. Used FileInfo to get the information related to the file.


FileInfo FI = new FileInfo(Path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid DataGrd = new DataGrid();
DataGrd.DataSource = dt1;
DataGrd.DataBind();

DataGrd.RenderControl(htmlWrite);
string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}

System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
stringWriter.ToString().Normalize();
vw.Write(stringWriter.ToString());
vw.Flush();
vw.Close();
WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());

The above code uses a WriteAttachment function which pushes the attachment to the user in the Response object. The following code shows the implementation of WriteAttachment:


public static void WriteAttachment(string FileName, string FileType, string content)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = FileType;
Response.Write(content);
Response.End();
}

Hope it can help you.


Best Regards,

Amy Peng 


[RESOLVED] An unhandled exception occurred during the execution of the current web request


Hi,

When the project is being called, I get this





Server Error in '/App9' Application.

--------------------------------------------------------------------------------





Buffer cannot be null.

Parameter name: buffer

  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.




 Exception Details: System.ArgumentNullException: Buffer cannot be null.

Parameter name: buffer



Source Error:





 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  



Stack Trace:







[ArgumentNullException: Buffer cannot be null.

Parameter name: buffer]

   System.IO.MemoryStream..ctor(Byte[] buffer, Boolean writable) +14187065

   App9.Detail.Page_Load(Object sender, EventArgs e) +3136

   System.Web.UI.Control.LoadRecursive() +71

   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178



 





--------------------------------------------------------------------------------

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044 




Why?



Any help?



Any help?



Hi,


Please try to put a breakpoint and debug your code line by line.


Because you do not provide your code here, please try to refer to these similar threads:


http://social.msdn.microsoft.com/Forums/vstudio/en-US/b0f809ee-e673-4b23-9189-48bca44e45e3/buffer-cannot-be-null.


http://stackoverflow.com/questions/1892591/buffer-cannot-be-null-parameterbuffer.


http://www.dreamincode.net/forums/topic/308658-buffer-cannot-be-null/ .


Hope it can help you.


Best Regards,

Amy Peng 


 


[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] 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] Grid View Update


Dear Friends,


                 I am inserting data from grid using button control. Hence there is no Button controls inside the grid.


When loading the grid at first time initially first row will be there and if i click the "Add" button means rows will create. For this my code part is,


#region SetInitialRowforTransfer

///



/// SetInitialRowforTransfer

///


private void SetInitialRowforTransfer()

{

try

{

DataTable dt = new DataTable();


DataRow dr = null;


dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));


dt.Columns.Add(new DataColumn("Column1", typeof(string)));


dt.Columns.Add(new DataColumn("Column2", typeof(string)));


dt.Columns.Add(new DataColumn("Column3", typeof(string)));


dt.Columns.Add(new DataColumn("Column4", typeof(string)));


dt.Columns.Add(new DataColumn("Column5", typeof(string)));


dt.Columns.Add(new DataColumn("Column6", typeof(string)));


dt.Columns.Add(new DataColumn("Column7", typeof(string)));


dr = dt.NewRow();


dr["RowNumber"] = 1;


dr["Column1"] = string.Empty;


dr["Column2"] = string.Empty;


dr["Column3"] = string.Empty;


dr["Column4"] = string.Empty;


dr["Column5"] = string.Empty;


dr["Column6"] = string.Empty;


dr["Column7"] = string.Empty;


dt.Rows.Add(dr);


//dr = dt.NewRow();



//Store the DataTable in ViewState


ViewState["CurrentTableforTransfer"] = dt;



gvContact.DataSource = dt;


gvContact.DataBind();

}

catch (Exception ex)

{


throw ex;

}




}

#endregion


#region AddNewRowToGridforTransfer

///



/// AddNewRowToGridforTransfer

///


private void AddNewRowToGridforTransfer()

{

try

{


int rowIndex = 0;



if (ViewState["CurrentTableforTransfer"] != null)

{


DataTable dtCurrentTable = (DataTable)ViewState["CurrentTableforTransfer"];


DataRow drCurrentRow = null;


if (dtCurrentTable.Rows.Count > 0)

{


for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)

{


//extract the TextBox values


TextBox box1 = (TextBox)gvContact.Rows[rowIndex].Cells[1].FindControl("txtTransferPLaceFrom");


TextBox box2 = (TextBox)gvContact.Rows[rowIndex].Cells[2].FindControl("txtDesignTransfer");


TextBox box3 = (TextBox)gvContact.Rows[rowIndex].Cells[3].FindControl("txtTansferDate");


TextBox box4 = (TextBox)gvContact.Rows[rowIndex].Cells[4].FindControl("txtToPlace");


TextBox box5 = (TextBox)gvContact.Rows[rowIndex].Cells[5].FindControl("txtJoiningDate");


TextBox box6 = (TextBox)gvContact.Rows[rowIndex].Cells[6].FindControl("txtTransferReason");


TextBox box7 = (TextBox)gvContact.Rows[rowIndex].Cells[7].FindControl("txtTransferemail");



drCurrentRow = dtCurrentTable.NewRow();


drCurrentRow["RowNumber"] = i + 1;



dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;


dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;


dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;


dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;


dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;


dtCurrentTable.Rows[i - 1]["Column6"] = box6.Text;


dtCurrentTable.Rows[i - 1]["Column7"] = box7.Text;



rowIndex++;


}


dtCurrentTable.Rows.Add(drCurrentRow);


ViewState["CurrentTableforTransfer"] = dtCurrentTable;



gvContact.DataSource = dtCurrentTable;


gvContact.DataBind();


}


}


else

{


Response.Write("ViewState is null");


}



//Set Previous Data on Postbacks


SetPreviousDataforTransfer();

}

catch (Exception ex)

{


throw ex;

}


}

#endregion


#region SetPreviousDataforTransfer

///



/// SetPreviousDataforTransfer

///


private void SetPreviousDataforTransfer()

{


try

{

int rowIndex = 0;


if (ViewState["CurrentTableforTransfer"] != null)

{


DataTable dt = (DataTable)ViewState["CurrentTableforTransfer"];


if (dt.Rows.Count > 0)

{


for (int i = 0; i < dt.Rows.Count; i++)

{


TextBox box1 = (TextBox)gvContact.Rows[rowIndex].Cells[1].FindControl("txtTransferPLaceFrom");


TextBox box2 = (TextBox)gvContact.Rows[rowIndex].Cells[2].FindControl("txtDesignTransfer");


TextBox box3 = (TextBox)gvContact.Rows[rowIndex].Cells[3].FindControl("txtTansferDate");


TextBox box4 = (TextBox)gvContact.Rows[rowIndex].Cells[4].FindControl("txtToPlace");


TextBox box5 = (TextBox)gvContact.Rows[rowIndex].Cells[5].FindControl("txtJoiningDate");


TextBox box6 = (TextBox)gvContact.Rows[rowIndex].Cells[6].FindControl("txtTransferReason");


TextBox box7 = (TextBox)gvContact.Rows[rowIndex].Cells[7].FindControl("txtTransferemail");




box1.Text = dt.Rows[i]["Column1"].ToString();


box2.Text = dt.Rows[i]["Column2"].ToString();


box3.Text = dt.Rows[i]["Column3"].ToString();


box4.Text = dt.Rows[i]["Column4"].ToString();


box5.Text = dt.Rows[i]["Column5"].ToString();


box6.Text = dt.Rows[i]["Column6"].ToString();


box7.Text = dt.Rows[i]["Column7"].ToString();



rowIndex++;


}


}


}


}

catch (Exception ex)

{


throw ex;

}

}

#endregion


#region ButtonAddfoTransfer_Click

///



/// ButtonAddfoTransfer_Click

///


///

///

protected void ButtonAddfoTransfer_Click(object sender, EventArgs e)

{


AddNewRowToGridforTransfer();


}

#endregion



Then i can insert the data by using following Insert code,


#region InsertGridTransferDetails


public void InsertGridTransferDetails(int sid)

{

BO_ObjSupplierMaster = new BO_Supplier_Master();

BE_ObjSupplierContact = new BE_Supplier_Contact();

try

{


foreach (GridViewRow row in gvContact.Rows)

{


TextBox txtplacefrm = (TextBox)row.FindControl("txtTransferPLaceFrom");

TextBox txtdesigntransfer = (TextBox)row.FindControl("txtDesignTransfer");

TextBox txttransferdate = (TextBox)row.FindControl("txtTansferDate");

TextBox txttoplace = (TextBox)row.FindControl("txtToPlace");

TextBox txtjoindate = (TextBox)row.FindControl("txtJoiningDate");

TextBox txttransferreason = (TextBox)row.FindControl("txtTransferReason");

TextBox txttransferemail = (TextBox)row.FindControl("txtTransferemail");


BE_ObjSupplierContact.Sup_Con_Lname1 = txtplacefrm.Text;

BE_ObjSupplierContact.Sup_Con_Mname1 = txtdesigntransfer.Text;

BE_ObjSupplierContact.Sup_Con_Fname1 = txttransferdate.Text;


BE_ObjSupplierContact.Sup_Con_Title1 = txttoplace.Text;

BE_ObjSupplierContact.Sup_Con_Telephone1 = txtjoindate.Text;

BE_ObjSupplierContact.Sup_Con_Mob1 = txttransferreason.Text;

BE_ObjSupplierContact.Sup_Con_Email1 = txttransferemail.Text;


BE_ObjSupplierContact.Sup_Master_Key1 = Convert.ToInt16(sid);


BO_ObjSupplierMaster.InsertSupplierContact(BE_ObjSupplierContact);


}





}

catch (Exception ex)

{


throw ex;

}

}

#endregion



Front end code is,



BorderColor="#A01E1E" Width="85%" HeaderStyle-Height="40px" RowStyle-Height="30px"

RowStyle-BorderColor="#A01E1E" runat="server" ShowFooter="true" AutoGenerateColumns="false">
















































































Text="Add" />









Now i want to Update the record. How can i bind the data to the grid. Please guide me to bind the data.



hey, once you add a new row to datatable, you can rebind the datatable to gridview again as


gvContact.DataSource = dtCurrentTable;


gvContact.DataBind();



and it will automatically update record



Hi,


Goto following link it has shown insert,update and delete inline.


http://www.codeproject.com/Articles/24085/Insert-Update-Delete-with-Gridview-Simple-Way


[RESOLVED] Export ExcelFile to grid View


Hi, I want to import an excel file(file name: tp30.xls, having one sheet name: tp30) in a gridView. Every time I get a Exception....


Syntax error (missing operator) in query expression 'Valuated stock'.


near the line.....    da.Fill(ds);    ( or, da.Fill(ds,"[tp30$]"); )


here is my codes........


protected void Button2_Click(object sender, EventArgs e)
{
string connString = "";
string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
string path = FileUpload1.PostedFile.FileName;
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT Material,Valuated stock FROM [tp30$]";
OleDbConnection conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
da.Dispose();
conn.Close();
conn.Dispose();
}
}

The aspx code.....
































It simply does not understand that Valuated stock is one word and not 2 different names. 


Try


string query = "SELECT Material,[Valuated stock] FROM [tp30$]";


I have Solve it!!!



Hi San,

Try this

 string query = "SELECT Material,[Valuated stock] FROM [tp30$]";



Sql didn't allow space between the name of column.so you need to put the name in square bracket.

hope this will help you out .

[RESOLVED] Validations controls causing problems


hello 


i am designing a form where there are some textboxes along with validations on the form and user is submiting data in the textboxes on click of save button.


also there is a datagrid in bottom of the form where data from table in the database is showing and ser is able to update the data in the grid delete row, update.


sometimes it happens that user just update or delete rows from the grid and don't enter the data in the textboxes which are also present on the form along with the validations and when user clicks update or delete button on grid that action don't takes place
instead validaions control shows errors. how to handel this problem?


thanx in advance 



Specify
ValidationGroup
property


I guess (not sure) if you use ValidationGroup only on Form validation, it will work. Set ValidationGroup property to all validators in Form and Also set ValidationGroup property of button


Or you can set different validation groups for form and gridview.


Regards



You can set other buttons causesvalidation="false"

[RESOLVED] Search/Filter GridView - SQL Stored Proc or DataTable (Efficiency)?


I have a GridView containing Employee data and want to be able to search/filter the results.


What is the most efficient way to do this out of the options below (or maybe another option)?


1. SQL Stored Proc with various Parameters (EmployeeID, FirstName, LastName, Manager, etc) meaning that only matched results are returned to the GridView.


2. DataTable containing the entire Employee dataset (approx 3,000 employees) from a simple SQL Stored Proc that returns all employee records. Handle the filtering of the DataTable in code behind.


My gut feeling is that option 1 would be more efficient (in a way) because you are only passing a limited number of employee records from the [seperate] database server to the app/web server. Also, it means that large DataTables will not be held in memory.


On the other hand, option 1 would potentially result in many more calls to the database server, whereas option 2 would be a one time call.



I would still prefer option 1... since it will be clean, more maintainable and typical search operation is generally not invoked very repetadely


also, if number of users grows in future then, for search operation by every user, it will store data in server memory... so, not a good approach in terms of scalability


hope this helps...


[RESOLVED] From Visual Studio in “design view”, is possible to have the correspondig lines of code highlighted in “source view”?


I use VS2010 with GridView, FormView ecc...


I frequently switch from Design View (in which for example I am visually editing something inside a FormView EditItemTemplate), to Source View.


Note that this happen when I am editing something inside a EditItemTemplate


So, for example if in Design View I have a TextBox selected, when I switch to Source View I'd like to have ONLY the corresponding lines selected, instead VS2010 highligh ALL the FormView EditItemtemplate code, from start to finish (which can be 1000 lines
long!).


Is possible or not to instruct VS to select only the relevant lines?




No it is not posible.



Because gridview is one control and you are placing another controls inside it. So it is consider as part fo grid view so it will select whole grid view. And also you can not directly access that control in code behind just because of same reason.




Wait!


Now it is functioning correctly!


From Design view:



  1. I select an TextBox --> ... is selected in source view
  2. I click in a cell -->
  3. I highligh a full table row in design --> the code inside ... is selected in source, wonderful!


From source view:



  1. I click wherever in a line inside the whole table is highlighted in design view
  2. I click inside a the control is highlighted in design view

  3. WONDERFUL!!! Surprised


    So, what the hell has got messed before, and what I have done in the meantime that reset things?


    (In the meantime I have close and reopend VS (not working), rebuild solution, refactored code, reformatted code, changed formatting tag options, ecc...)



    Arrghhh!!!


    I edited the code from the Source view, removing a

    line, the VS asked me to refresh the view, claiming that Design view is out of sync with Source view.


    I clicked to synchronize view, and now it's not functioning anymore!!! Yell


    I thought it could be because some background VS task didn't have yet enough time to complete, so I waited ... but after something like 10 minutes of wait it's not working yet....


    So, I clicked undo to insert the

    lines back... and (not so surprisingly) the highlight works again!!!


    What is happening???



    PS: Important info. If instead I remove the

    line from the Design view, via mouse dx popup menu-->Delete rows-->Delete row the Source/Design remains in synch and the highlight functionality continue working Undecided



    Up to now I have found this workaround... that seems to be working :-)


    You have manually edited the source code, so messing up the synchronize with design view...!



    1. Select a control in Design view
    2. Change something in the Properties window, (for example set width=100px, or toggle the Enabled property)
    3. WAIT.... (your change forces VS to update the source code!)
    4. After some time (something like 5-10 seconds for my slow machine ;-)), VS updates the code, adding/changing the relevant code 
    5. And now the bidirectional highlight functionality works again!
    6. Remember to Change back/Toggle the modified property Tongue Out 

    [RESOLVED] Allow user to SELECT TIME


    Within my DetailsView I have added a DATE selection that allows the user to select a specific date using a Calendar feature… this was achieved using the below code


     <%@ Register TagPrefix="asp" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit"%>


     



       



                 


                 




    What I need now is to allow the user to select a TIME feature of 15 minutes. So the user can select 15, 30, 45, etc… what is the best way I can do this?



    Look what I found. http://tarruda.github.io/bootstrap-datetimepicker/ Its awesome. Cool



    if you are comfortable with ajax-tool-kit then follow this ,


    http://www.ajaxcontroltoolkit.com/NumericUpDown/NumericUpDown.aspx its cool Smile


    [RESOLVED] file download link within the gridview and perform download


    hi,


     am having a gridview with path to the  file.name , where file is  physically stored in the filesystem and am storing the filepath in my db table column.so, i need to pull that path and show it in grdiview column. and when user clicks on the document link,
    user shud be able to download the file .


    i was  able to show the  document name as link in the gridview , but i am unable to download properly.also, the document extension can be anything/ docx, xlsx,txt,ppt, pdf etc. how to implement this download.


    or


    should i store the file name and data/content in the  sql db itself as  varbinary(max) datatype.? and in that case, how to retrieve the content to download



    Since it's just part of the filesystem, you can't link to it directly as you would need to have a virtual path, ie: a web-path and not a server-side path (as in: C:\myfiles\mydirectory\myfile.doc). If you use a LinkButton, you can set the commandargument
    for it to be the file path, then for the command event try the following


    string path = e.CommandArgument.ToString();
    if(File.Exists(path))
    {
    Response.Clear();
    Response.TransmitFile(path);
    Response.Flush();
    }

    You can add custom logic for adding an appropriate content type so the browser will understand what to do with the file.





    BenjaminKNR


    i was  able to show the  document name as link in the gridview , but i am unable to download properly.also, the document extension can be anything/ docx, xlsx,txt,ppt, pdf etc. how to implement this download.


    Leave file in the filesystem.


    Your files should be within your website directory


    Suppose there is folder Name Files in your website



    Set link in your gridview like "www.yoursite.com/Files/YourFile.txt" for files


    Make sure permissions are set to read and download files from that folder


    Regards




    if (e.CommandName == "Download")
    {
    try
    {
    string filename = e.CommandArgument.ToString();
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment;filename=Archiving.pdf");
    Response.TransmitFile(Server.MapPath(filename ));
    Response.End();
    }
    catch (Exception ex)
    {
    }
    }

    Im using LinkButton inside gridview where Command Argument =File Path 


    Up Code For Download Any file .pdf and you can use Switch Statement for download any type


    regards



    If you want add download link column to gridview, save virtual path to filepath field. Virtual path like : filename.ext or folder/filename.ext or ~/folder/subfolder/filename.ext

    [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] Object reference not set to an instance of an object.


    Hi,

    After having added the following assignment statement,


    SqlCommand cmd = new SqlCommand("SELECT top 1 dpt_id,dpt_name,fld2,fld3,CONVERT(varchar,fld4,105) fld4,fld5,photo_fld6,fld12,fld131,fld132,CONVERT(varchar,fld10,22) as col_fld7, CONVERT(varchar,fld11,22) as col_fld9 FROM dpt where LTRIM(RTRIM(dpt_abbr))=@par_id and LTRIM(RTRIM(dpt_fld8))=@par_fld8", conn);

    ...
    reader = cmd.ExecuteReader();

    if (reader.HasRows)
    //if (reader.Read())
    {
    reader.Read();
    tb_dptname.Text = reader["dpt_name"].ToString();
    tb_fld2.Text = reader["fld2"].ToString();
    tb_fld3.Text = reader["fld3"].ToString();
    tb_fld4.Text = reader["fld4"].ToString();
    tb_fld5.Text = reader["fld5"].ToString();
    tb_ph_fld6.Text = reader["photo_fld6"].ToString();
    tb_fld7.Text = reader["col_fld7"].ToString();
    ...





    I get this eror. why?


    Server Error in '/App10' Application.

    --------------------------------------------------------------------------------





    Object reference not set to an instance of an object.

      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.




     Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.



    Source Error:





     An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  



    Stack Trace:







    [NullReferenceException: Object reference not set to an instance of an object.]

       App10.Detail.Pfld5_Load(Object sender, EventArgs e) +1755

       System.Web.UI.Control.LoadRecursive() +70

       System.Web.UI.Pfld5.ProcessRequestMain(Boolean includeStfld5sBeforeAsyncPoint, Boolean includeStfld5sAfterAsyncPoint) +3177



     





    --------------------------------------------------------------------------------

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044  





    what it is here?




    wmec


    App10.Detail.Pfld5_Load(Object sender, EventArgs e) +1755



    Where you place the textboxes? If in another control use FindControl. You also check the textbox id typed correctly.

    put a break point and check if tb_fld5.Text
    is null or blank



    Oned,

    All the Textboxes shown above are available for being selected and I got no error when building the project, why do I need to to Findcontrol for them?





    check if you are having control with the same id on another page.



    Oned,

    I've got the same error even if I use FindControl to declare the same set of TextBox again.



    Gaurav,

    Do you mean it is due to the same name of Textbox is being reused?





    Here are some of possible reasons for this exception;



    2 - cmd.Connection might not have instantiated like;


    _SqlCommand.Connection = new SqlConnection("ConnectionString");

    3-





    I would consider placing a breakpoint in the code above to determine exactly where the error is occurring at.


    However since it is a Null Reference Exception, you are attempting to access a property from a null object which can commonly occur using the
    Object.ToString() method which could be happening in the code below : 


    //You will need to ensure that your reader["key"] object is not null for each of these elements
    tb_dptname.Text = reader["dpt_name"].ToString();
    tb_fld2.Text = reader["fld2"].ToString();
    tb_fld3.Text = reader["fld3"].ToString();
    tb_fld4.Text = reader["fld4"].ToString();
    tb_fld5.Text = reader["fld5"].ToString();
    tb_ph_fld6.Text = reader["photo_fld6"].ToString();
    tb_fld7.Text = reader["col_fld7"].ToString();

    It's likely that one of the above columns being refereced from your reader doesn't exist, so when you attempt to use the ToString() method on one of these null objects you are recieving your error.


    I would highly recommend using the breakpoint method to determine exactly where this is happening at (as it could be an issue as simple as a spelling error)




    Thanks all. I also don't know why it is fine when I now directly run the project. But I've got the ssame error, once it (which is the same deployed project) is being called by one other project.



    How to set a pause within the project, to debug the deployed project?


    Right now, once I've enabled the following 2 lines in bold, the problem will come out. If I have disabled these 2 lines, then no problem.

                    SqlCommand cmd = new SqlCommand("SELECT top 1 dpt_id,dpt_name,fld2,fld3,CONVERT(varchar,fld4,105) fld4,fld5,photo_fld6,fld12,fld131,fld132,CONVERT(varchar,fld10,22) as col_fld7, CONVERT(varchar,fld11,22) as col_fld9 FROM dpt where LTRIM(RTRIM(dpt_abbr))=@par_id
    and LTRIM(RTRIM(dpt_fld8))=@par_fld8", conn);

                    ...



                    reader = cmd.ExecuteReader();



                    if (reader.HasRows)

                    {

                        reader.Read();

                        TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

                        tb_dptnm.Text = reader["dpt_name"].ToString();

                        ...

                        tot_rec++;

                    }





    Use Convert.ToString() instead of .toString(). it accepts even null values



    You mentioned that the following lines were causing your null reference issue : 


    TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;
    tb_dptnm.Text = reader["dpt_name"].ToString();

    If that is the case, then the odds are that the FindControl() method is unable to actually access or find your tb_dptnm Textbox Control within your form and since it cannot find it, it is attempting to set the Text property of null (which will cause your error). This can easily be checked by placing a breakpoint in the code and checking what the value of your tb_dptnm variable is after that line is executed.


    Another possiblility is that your reader["dpt_name"] value is null (in which case you are trying to use the ToString() method on it and will encounter the same problem.


    I would recommend first - check both of these values being used and ensure that the names "tb_dptname" and "dpt_name" match the ID value of your TextBox and the column being returned in your DataReader respectively.


    Secondly, you could simply add the necessary logic to check for nulls and basically ignore setting the value if it is null : 


    //Checks if the TextBox is null
    TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

    //The Textbox was found - set it's Text property
    if(tb_dptnm != null)
    {
    tb_dptnm.Text = reader["dpt_name"].ToString();
    }

    and 


    //Now it also checks if your reader["dpt_name"] name is null
    TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

    //The Textbox was found - set it's Text property
    if(tb_dptnm != null)
    {
    //Checks if your dpt_name value is not null
    if(reader["dpt_name"] != null)
    {
    tb_dptnm.Text = reader["dpt_name"].ToString();
    }
    }

    Alternatively, you can use the Convert.ToString() method which handles null values as well : 


    TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

    if(tb_dptnm != null)
    {
    tb_dptnm.Text = Convert.ToString(reader["dpt_name"]);
    }









    Hi,


    Put the reader in a while loopand use convert to string.


    SqlDataReader reader = command.ExecuteReader();

    // Call Read before accessing data. 
    while (reader.Read())
    {
    tb_fld5.Text = Convert.tostring(reader[""]);
    }

    // Call Close when done reading.
    reader.Close();

    if this not working can you please tell me at which line exception is throwing.



    Thanks


    Raj



    Thanks a lot Rion.

    Using "if" to check if "tb_dptnm" is null, is fine, but the relevant Textbox is really on the page like




            width="260px"
    Font-Names="Times New Roman"
    Font-Size="11pt"
    runat="server" />


    why is "tb_dptnm" null below, since the previous error disappears if I've put these?


    //Checks if the TextBox is null
    TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;

    //The Textbox was found - set it's Text property
    if(tb_dptnm != null)
    ...







    If that is how your TextBox appears, you should have no trouble accessing it through your code-behind simply by referring to its ID property :


    //The "tb_dptnm" Textbox being referenced by its ID property and the Text being set
    tb_dptnm.Text = "Example";

    My initial thought was that it could have something to do with the mark-up being invalid (as some of the properties being used such as Font-Size and a few others are not proper properties) or by explicitly defining a closing tag instead of the self-closing one as seen below : 



    If you are still encountering issues with accessing it through either the FindControl method or directly through its ID, I would recommend placing a breakpoint within the code and actually inspecting the element to see if it can be found.













    Thanks a lot. I put it like


            width="260px"
    Font-Names="Times New Roman"
    Font-Size="11pt"
    runat="server" >



    by adding the closing tag. But once I've removed that "if" condition in the codebehind, then I've got the same problem. Why?





    Any help?



    I can't think of why you would be unable to reference the control (unless it was contained within some other container element or within a Master Page or something).


    Try using the exact tag that I specified earlier : 


     ID="tb_dptname" Width="260" runat="server">

    and then attempt to reference the element within your code-behind directly by its ID (instead of using the FindControl() method) : 


    //Simply reference your TextBox by it's ID instead of using the FindControl() method
    tb_dptnm.Text = Convert.ToString(reader["dpt_name"]);

    If you are still encountering issues, you may want to consider posting your entire markup and code behind for the page in question and we can try and figure out exactly what could be causing this.





    Thanks a lot Rion. Using these


    //TextBox tb_dptnm = FindControl("tb_dptname") as TextBox;
    //if (tb_dptnm != null)
    //{
    //tb_dptnm.Text = reader["dpt_name"].ToString();
    //}
    tb_dptname.Text = Convert.ToString(reader["dpt_name"]);
    ...



    with exactly this Textbox on the page


                width="260px"
    runat="server" >





    I'm still getting the same problem.





    Server Error in '/App10' Application.

    --------------------------------------------------------------------------------





    Object reference not set to an instance of an object.

      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.




     Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.



    Source Error:





     An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  



    Stack Trace:







    [NullReferenceException: Object reference not set to an instance of an object.]

       App10.Detail.Page_Load(Object sender, EventArgs e) +1558

       System.Web.UI.Control.LoadRecursive() +70

       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3177



     





    --------------------------------------------------------------------------------

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044 



    I can't see anything wrong with the code that you are using and it should be working just fine.


    Have you tried placing a breakpoint and checked some of the values within your code to attempt to figure out exactly where your tb_dptname TextBox is located? The only thing that I can think of is that it is possibly located within another container element
    (which you might have to use to reference it from) or within another Row, Master Page, etc.


    You mentioned that your other values are working but the tb_dptname one is not. Could you post some additional code where the other TextBoxes are defined as well (any additional code would actually be helpful) so that we can try and figure out exactly
    what is going wrong here.



    Sorry, if I directly debug it in VS2012, I have got no problem.



    When it (that is the deployed) is being called by one other project, and it is only having these assignment statements for these 2 Textboxes, then I am still having the error.


    if (reader["dpt_name"] != null)
    {
    tb_dptname.Text = Convert.ToString(reader["dpt_name"]);
    }
    if (reader["fld2"] != null)
    {
    tb_fld2.Text = Convert.ToString(reader["fld2"]);
    }
    if (reader["fld3"] != null)
    {
    tb_fld3.Text = Convert.ToString(reader["fld3"]);
    }





    try like this


    if (reader["dpt_name"] != null)
    {
    if (reader["dpt_name"] != DBNull.Value)
    {
    ...
    }
    }







    Sorry, with only one assignment line for the Textbox, like


    if (reader["dpt_name"] != null)
    {
    if (reader["dpt_name"] != DBNull.Value)
    {
    tb_dptname.Text = Convert.ToString(reader["dpt_name"]);
    }
    }



                       

    I'm still having the same error.



    And just for clarification, this code is actually appearing in the same page (Web Form) that your TextBox control is declared in correct?


    As I noticed that you had mentioned it was being called from another Project, I just wanted to ensure that you weren't trying to access a TextBox that didn't appear on the actual Web Form itself.



    Yes, the current project is App10 and the code above is in Page_Load of this project.



    But the error is mentioning 'App10' even if 'App10' has been called by App9 project. The error means the current project is App10 right?





    Please check your asp page, and the code behind again.


    I believe you show different IDs, although I can't see them while I am typing this reply.


    One has a "name" suffix, while the other has a "nme" suffix.


    My mistake. The ID values are the same.


    I cannot retract this post. sorry.


     



    Any help please?



    Can you tell me what you see when you run the stored procedure from SSMS?


    Just curious if any rows are selected, and if any of the rows selected have NULL values.



    In SSMS, I see the relevant record with the same value of given parameters, is existing in the table.



    Hello,


    May I suggest that you change the textbox control name you have?


    TextBox tb_dptnm =
    FindControl("tb_dptname")
    as TextBox;


    Try something like tb_dptname_Testing.


    Make the change on one single ASP page, and then change the above FindControl, to locate the new TextBox.


    Also, after the FindControl, check the return code to ensure that it executed successfully.


    By changing the name to something relatively unique, you can ensure that the TextBox ID was not used on more than one single ASP page, and then by checkiing the return code, you will know that the FindControl actually executed successfully.


     


    Hope this helps.


    [RESOLVED] Exporting datalist and gridview to excel


    Hello Experts,


    I am having one datalist and gridview within datalist control. I need to export both of them as report in excel sheet. Like below


    sr.  Class  CreatedDate ModifiedDate


    1     Class1   25/5/2013   25/5/2013


    Students


    Sr.  Name Address Bdate


    1    Abc    test add  25/5/1990


    2    DEF   test add 2  25/3/1991


    sr.  Class  CreatedDate ModifiedDate


    2     Class2   25/6/2013   25/6/2013


    Students


    Sr.  Name Address Bdate


    1    Abc2    test add22  25/5/1990


    2    DEF2   test add 22  25/3/1991


    and so on.....


    Here the class display is datalist and student display is gridview.


    Please suggest how to achive that?


    Thank you.




    Refer bellow url


    http://www.aspsnippets.com/Articles/Export-GridView-To-WordExcelPDFCSV-in-ASP.Net.aspx



    Hi,


    Please try to refer to the following code about export data to excel (use the gridview as an example):


    protected void fillGrid()
    {
    string str = "SELECT [UNo], [EmpName], [Age],
    convert(char,[dob],103) dob FROM [tbl_EmpDetails]";

    myConnection = new SqlConnection(conn);
    myConnection.Open();
    myCommand = new SqlCommand(str, myConnection);
    SqlDataAdapter mySQLDataAdapter;
    myDataSet = new DataTable();
    mySQLDataAdapter = new SqlDataAdapter(myCommand);
    mySQLDataAdapter.Fill(myDataSet);
    GridView1.DataSource = myDataSet;
    GridView1.DataBind();
    ViewState["dtList"] = myDataSet;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    fillGrid();
    }
    }

    Now, after binding a Gridview, data is ready to get exported to an Excel file. Click on a button named Export to Excel. Used FileInfo to get the information related to the file.


    FileInfo FI = new FileInfo(Path);
    StringWriter stringWriter = new StringWriter();
    HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
    DataGrid DataGrd = new DataGrid();
    DataGrd.DataSource = dt1;
    DataGrd.DataBind();

    DataGrd.RenderControl(htmlWrite);
    string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
    if (!Directory.Exists(directory))
    {
    Directory.CreateDirectory(directory);
    }

    System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
    stringWriter.ToString().Normalize();
    vw.Write(stringWriter.ToString());
    vw.Flush();
    vw.Close();
    WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());

    The above code uses a WriteAttachment function which pushes the attachment to the user in the Response object. The following code shows the implementation of WriteAttachment:


    public static void WriteAttachment(string FileName, string FileType, string content)
    {
    HttpResponse Response = System.Web.HttpContext.Current.Response;
    Response.ClearHeaders();
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
    Response.ContentType = FileType;
    Response.Write(content);
    Response.End();
    }

    Hope it can help you.


    Best Regards,

    Amy Peng