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

2014年7月13日 星期日

[RESOLVED] dynamically assigning image to literal from code behind but image is not displaying on .aspx


in .aspx



in code behind ( load event of page )


 litTab.Text = "";


but image is not displaying... any idea



Add an HTML img to the literal


litTab.Text = " src='someimage.png'
/>"



ImageButton ib= new ImageButton(); ib.ImageUrl= "~/Images/home.png";

[RESOLVED] Code don't display the names of months in the Axis X


Hi there, hope in your help.


Why this code don't display the names of months in the Axis X?


Can you help me?

Thanks in advance.


Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = true;

Chart1.Series.Add("Series1");
Chart1.Series["Series1"].LabelFormat = "#,##";
Chart1.Series["Series1"].XValueMember = "month";
Chart1.Series["Series1"].YValueMembers = "number";

Chart1.Series["Series1"].ChartType = SeriesChartType.Spline;

Chart1.Series["Series1"].IsValueShownAsLabel = true;
Chart1.Series["Series1"].IsValueShownAsLabel = true;

Chart1.Series["Series1"]["ShowMarkerLines"] = "True";
Chart1.Series["Series1"]["ShowMarkerLines"] = "True";

Chart1.Series["Series1"].BorderWidth = 3;
Chart1.Series["Series1"].Color = Color.Red;

Chart1.DataSource = objCmd.ExecuteReader();
Chart1.DataBind();

Chart1.SaveImage(PNG, ChartImageFormat.Png);













http://social.msdn.microsoft.com/Forums/getfile/304564







cms9651







Try changing the AisX interval to 1 as opposed to 5000 in your mark up.



thank you very much!


[RESOLVED] How to retrieve Image from database and pass through query string


My question i have a image in database, i want to retrieve and show in my home page , when i change menu , the image will be move through querystriing on the next menu. and i use the asp imagecontrol to hold the image in the master pasge


Can You show me step by step process  from image retrieval from database to image show on pages..


can i make u understand?


Good Explaination will be highly appreciable





ramanujbasu



Can You show me step by step process  from image retrieval from database to image show on pages..





check this


http://aspsnippets.com/Articles/Display-Images-from-SQL-Server-Database-using-ASP.Net.aspx


hope this helps...



Hi,


About Inserting And Reading Image To/From Database in ASP.NET (Web Application) in Image Control:


http://www.c-sharpcorner.com/uploadfile/17e8f6/inserting-and-reading-image-tofrom-database-in-Asp-Net-web-application-in-image-control/


Hope it can help you


[RESOLVED] When going to previous page button disappears?


 



Hi,


I have a custom back button and when clicked it goes to the previous page but a button is missing and the size of other items is changed. Has anyone come accross this behavior? Thanks!


 



NM I redid the project using master pages and it working now



Hi,


I am very glad that you have solved your problem by yourself.


If you have any other problem, welcome to post it in the asp.net forums.


Best Regards,

Amy Peng 


[RESOLVED] prevent show image button


I bound image button to data in datalist, (image url saved) How to prevent show image button when data have not image.(image url=empty) because in this case (image url=empty) the image button show whit no image whit X

bind Visible property of the button like this


Visible ='<%# Eval("ImageUrl") == System.DbNull.Value ? False : True %>'







oned_gk



bind Visible property of the button like this
Visible ='<%# Eval("ImageUrl") == System.DbNull.Value ? False : True %>'





This is not work:




VB?


Try this


Visible ='<%# Not Isdbnull(Eval("ImageUrl")) %>'









oned_gk



VB?
Try this
Visible ='<%# Not Isdbnull(Eval("ImageUrl")) %>'







this is not work, when the imagurl = null the imagebutton show whit X



protected void dlstControl_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{

((ImageButton)e.Item.Controls[Your ImageButton Index]).Visible =
((YourDataSourceType)e.Item.DataItem).ImageUrlProperty == null ? true : false;

//OR
((ImageButton)e.Item.Controls[Your ImageButton Index]).Visible =
((ImageButton)e.Item.Controls[Your ImageButton Index]).ImageUrl == null ? true : false;
}
}





mehr_83



this is not work, when the imagurl = null the imagebutton show whit X





Make sure the value is null instead empty string


For empty string try this


Visible ='<%# IIF(Eval("ImageUrl")="",false,true) %>'









oned_gk



VB?
Try this
Visible ='<%# Not Isdbnull(Eval("ImageUrl")) %>'







excuse me, this is work.


but


how to check the imagurl isempty and not checkto null



Make all empty string


ISNULL(IMAGEURL,'') as IMG


String.IsNullOrEmpty(Convert.ToString(Eval("ImageUrl")))? ...






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


Hi,


I have some problems loading my image file into the gridview control.


Please see screenshot: http://imageshack.us/photo/my-images/708/92zh.jpg/


Image handling ashx file:


public void ProcessRequest(HttpContext context)

{

objCmd.CommandText = "Select ImgSrc from M_DMemPict" + " where ImageId=@ImageId";

objCmd.CommandType = System.Data.CommandType.Text;

objCmd.Connection = objConn;

SqlParameter ImageID = new SqlParameter("@ImageId", System.Data.SqlDbType.Int);

ImageID.Value = context.Request.QueryString["img"];

objCmd.Parameters.Add(ImageID);

objConn.Open();

SqlDataReader dReader = objCmd.ExecuteReader();

dReader.Read();

context.Response.BinaryWrite((byte[])dReader["ImgSrc"]);

dReader.Close();

objConn.Close();


context.Response.ContentType = "image/jpeg";

context.Response.AppendHeader("Content-Disposition", "attachment; filename=test.JPG");

//context.Response.TransmitFile(@"D:\\test.jpg");

//context.Response.End();


}


Please help, thanks.



Check your query first at the Database , did it returns the column "ImageId" or not.



this is the case of since your query doest not returns the column ImageId



@Rjk_P,


my query is correct however could you please correct this syntax from the gridview control using templatefield tag.



ImageUrl='<%# "~/ImgHandler.ashx?id=" + Eval("ImageId")%>'/>


The image is not displaying on the gridview. 


Thanks.



Your are passing id as parmenter and taking img as  request context querysting value at server side. Change it and try..



Hi,


The error is DataBinding:System.Data.DataRowView" does not contain a property with the name 'ImageId'.


So please try to check if you have a column named 'ImageId', Or you have mistake the name of the column.


Hope it can help you.


Best Regards,

Amy Peng 


[RESOLVED] FINDING THE TOOL


IT IS SIMILAR TO GRIDVIEW WITH COLUMNS AS ROWS AND WITH A HORIZONTAL SCROLL BAR.  THE IMAGE WAS IN VB PROJECT. I WANT IN ASP.NET




[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] dynamically assigning image to literal from code behind but image is not displaying on .aspx


in .aspx



in code behind ( load event of page )


 litTab.Text = "";


but image is not displaying... any idea



Add an HTML img to the literal


litTab.Text = " src='someimage.png'
/>"



ImageButton ib= new ImageButton(); ib.ImageUrl= "~/Images/home.png";

[RESOLVED] Code don&#39;t display the names of months in the Axis X


Hi there, hope in your help.


Why this code don't display the names of months in the Axis X?


Can you help me?

Thanks in advance.


Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = true;

Chart1.Series.Add("Series1");
Chart1.Series["Series1"].LabelFormat = "#,##";
Chart1.Series["Series1"].XValueMember = "month";
Chart1.Series["Series1"].YValueMembers = "number";

Chart1.Series["Series1"].ChartType = SeriesChartType.Spline;

Chart1.Series["Series1"].IsValueShownAsLabel = true;
Chart1.Series["Series1"].IsValueShownAsLabel = true;

Chart1.Series["Series1"]["ShowMarkerLines"] = "True";
Chart1.Series["Series1"]["ShowMarkerLines"] = "True";

Chart1.Series["Series1"].BorderWidth = 3;
Chart1.Series["Series1"].Color = Color.Red;

Chart1.DataSource = objCmd.ExecuteReader();
Chart1.DataBind();

Chart1.SaveImage(PNG, ChartImageFormat.Png);













http://social.msdn.microsoft.com/Forums/getfile/304564







cms9651







Try changing the AisX interval to 1 as opposed to 5000 in your mark up.



thank you very much!


[RESOLVED] How to retrieve Image from database and pass through query string


My question i have a image in database, i want to retrieve and show in my home page , when i change menu , the image will be move through querystriing on the next menu. and i use the asp imagecontrol to hold the image in the master pasge


Can You show me step by step process  from image retrieval from database to image show on pages..


can i make u understand?


Good Explaination will be highly appreciable





ramanujbasu



Can You show me step by step process  from image retrieval from database to image show on pages..





check this


http://aspsnippets.com/Articles/Display-Images-from-SQL-Server-Database-using-ASP.Net.aspx


hope this helps...



Hi,


About Inserting And Reading Image To/From Database in ASP.NET (Web Application) in Image Control:


http://www.c-sharpcorner.com/uploadfile/17e8f6/inserting-and-reading-image-tofrom-database-in-Asp-Net-web-application-in-image-control/


Hope it can help you


[RESOLVED] When going to previous page button disappears?


 



Hi,


I have a custom back button and when clicked it goes to the previous page but a button is missing and the size of other items is changed. Has anyone come accross this behavior? Thanks!


 



NM I redid the project using master pages and it working now



Hi,


I am very glad that you have solved your problem by yourself.


If you have any other problem, welcome to post it in the asp.net forums.


Best Regards,

Amy Peng 


[RESOLVED] prevent show image button


I bound image button to data in datalist, (image url saved) How to prevent show image button when data have not image.(image url=empty) because in this case (image url=empty) the image button show whit no image whit X

bind Visible property of the button like this


Visible ='<%# Eval("ImageUrl") == System.DbNull.Value ? False : True %>'







oned_gk



bind Visible property of the button like this
Visible ='<%# Eval("ImageUrl") == System.DbNull.Value ? False : True %>'





This is not work:




VB?


Try this


Visible ='<%# Not Isdbnull(Eval("ImageUrl")) %>'









oned_gk



VB?
Try this
Visible ='<%# Not Isdbnull(Eval("ImageUrl")) %>'







this is not work, when the imagurl = null the imagebutton show whit X



protected void dlstControl_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{

((ImageButton)e.Item.Controls[Your ImageButton Index]).Visible =
((YourDataSourceType)e.Item.DataItem).ImageUrlProperty == null ? true : false;

//OR
((ImageButton)e.Item.Controls[Your ImageButton Index]).Visible =
((ImageButton)e.Item.Controls[Your ImageButton Index]).ImageUrl == null ? true : false;
}
}





mehr_83



this is not work, when the imagurl = null the imagebutton show whit X





Make sure the value is null instead empty string


For empty string try this


Visible ='<%# IIF(Eval("ImageUrl")="",false,true) %>'









oned_gk



VB?
Try this
Visible ='<%# Not Isdbnull(Eval("ImageUrl")) %>'







excuse me, this is work.


but


how to check the imagurl isempty and not checkto null



Make all empty string


ISNULL(IMAGEURL,'') as IMG


String.IsNullOrEmpty(Convert.ToString(Eval("ImageUrl")))? ...






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


Hi,


I have some problems loading my image file into the gridview control.


Please see screenshot: http://imageshack.us/photo/my-images/708/92zh.jpg/


Image handling ashx file:


public void ProcessRequest(HttpContext context)

{

objCmd.CommandText = "Select ImgSrc from M_DMemPict" + " where ImageId=@ImageId";

objCmd.CommandType = System.Data.CommandType.Text;

objCmd.Connection = objConn;

SqlParameter ImageID = new SqlParameter("@ImageId", System.Data.SqlDbType.Int);

ImageID.Value = context.Request.QueryString["img"];

objCmd.Parameters.Add(ImageID);

objConn.Open();

SqlDataReader dReader = objCmd.ExecuteReader();

dReader.Read();

context.Response.BinaryWrite((byte[])dReader["ImgSrc"]);

dReader.Close();

objConn.Close();


context.Response.ContentType = "image/jpeg";

context.Response.AppendHeader("Content-Disposition", "attachment; filename=test.JPG");

//context.Response.TransmitFile(@"D:\\test.jpg");

//context.Response.End();


}


Please help, thanks.



Check your query first at the Database , did it returns the column "ImageId" or not.



this is the case of since your query doest not returns the column ImageId



@Rjk_P,


my query is correct however could you please correct this syntax from the gridview control using templatefield tag.



ImageUrl='<%# "~/ImgHandler.ashx?id=" + Eval("ImageId")%>'/>


The image is not displaying on the gridview. 


Thanks.



Your are passing id as parmenter and taking img as  request context querysting value at server side. Change it and try..



Hi,


The error is DataBinding:System.Data.DataRowView" does not contain a property with the name 'ImageId'.


So please try to check if you have a column named 'ImageId', Or you have mistake the name of the column.


Hope it can help you.


Best Regards,

Amy Peng 


[RESOLVED] FINDING THE TOOL


IT IS SIMILAR TO GRIDVIEW WITH COLUMNS AS ROWS AND WITH A HORIZONTAL SCROLL BAR.  THE IMAGE WAS IN VB PROJECT. I WANT IN ASP.NET




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