2014年7月13日 星期日

[RESOLVED] displaying label values in multiline text from gridview


i got 1 gridview which has hyperlink in one column, wen the user clicks the link he will be directed to another page where the details of particular row will be displayed using individual labels. In those labels one of the label must be multilined for me
coz the text will be too long...


Please help me how to get that .


aspx page of label




Hi,


Just go through this post once: http://forums.asp.net/t/1323030.aspx



su88rao






nt useful... any othr solution ?




This problem could be because of absolute sizing or positioning of the label. don't specify the size of label and don't wrap it in absolutely sized container like panel and it will work fine.



i got the solution... by adding style="word-wrap:break-word;" to label and removing the height property of label can achieve tht 




<asp:Label ID="LblDescription" runat="server"
Font-Bold="True" Font-Names="Verdana"
Font-Size="X-Small" ForeColor="#0061C1" Height="16px"
Width="97px" BorderColor="#0061C1"
BorderWidth="1px" style="word-wrap:break-word;" BackColor="White"></asp:Label>

[RESOLVED] How to create time countdown in datalist or gridview


Hi, I'm trying to make public auction list. And I need time countdown for every row in datalist or gridview. How do I create time countdown in datalist or gridview using Asp.Net/C#?




Have a look at this link,


How to display a timer countdown inside my Gridview:

http://forums.asp.net/t/1743407.aspx/1



Thanks sridhar_rs. I solved my problem.


.aspx




























codebehind


protected void Timer1_Tick(object sender, EventArgs e)
{

foreach (GridViewRow item in GridView1.Rows)
{
var label2 = item.FindControl("Label2") as Label;

var label3 = item.FindControl("Label3") as Label;
var time2 = DateTime.Parse(label3.Text);
label.Text = (time2 - DateTime.Now).Days + " Day " + (time2 - DateTime.Now).Hours + " Hours " + (time2 - DateTime.Now).Minutes + " Minutes " + (time2 - DateTime.Now).Seconds + " Seconds";
}

}




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


hi


i am new in asp.net


i have a problem to search data from gridview


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


now i want to search record from that


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


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


please help me


thanks in advance





Vjitendra



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


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





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


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


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


How do I limit the number of rows per page in a listview



inside layout template of listview, add datapage tab as below


set pagesize in datapager tag







hope this helps...



If you're using a datapager, you can do something like shown below:


<asp:DataPager ID="myPager" runat="server" PagedControlID="Your ListView Id"
PageSize=
"5">


[RESOLVED] Gridview adding two Eval to the same Item Template label....


I have an gridview and I need to put the lastname and firstName in the same column, how do I add the firstname and lastname to the same column?



Code:




 

  





'' >



This too will work




[RESOLVED] Error Help Requested


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


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


 


    


       


      Filter by: Category :        


       


 and Supplier :        


    


 


    



 



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


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


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

or u can add assembly in web.config


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


hope this helps...



Thank you very much.


[RESOLVED] Detailsview null value


I want to check the value in Date Shipped. If there isn't anything in it, it won't allow the user to move on to the next page. I created a Session to check, but it never has a null value. I'm not sure why.


protected void Page_Load(object sender, EventArgs e)
{
lblError.Visible = false;
ShippingError.Visible = false;
CanceledError.Visible = false;
dvAddress.Visible = false;
dvCustomer.Visible = false;

}
protected void btnPacking_Click(object sender, EventArgs e)
{
Session["OrderID"] = dvOrder.SelectedValue;

if (Session["OrderID"] != null)
{
if (Session["Shipped"] != null)
{
Response.Redirect("~/PackageManagement/Packing2.aspx");
}
else
{
ShippingError.Visible = true;
}
}

else
{
lblError.Visible = true;
}
}

protected void dvOrder_DataBound(object sender, EventArgs e)
{


if (dvOrder.SelectedValue != null)
{
Label AddressID = dvOrder.FindControl("lblAddressID") as Label;
Address.Text = AddressID.Text;
Session["Address1"] = AddressID.Text;

if (dvOrder.CurrentMode == DetailsViewMode.ReadOnly)
{
Label Shipped = dvOrder.FindControl("lblShipped") as Label;
Session["Shipped"] = Shipped.Text;


}
dvAddress.Visible = true;
dvAddress.DataBind();
}
else
{
dvAddress.Visible = false;
}

}

    











































































Maybe you need to check for empty string instead. Or use the string isnullorempty().



Try as:


protected void btnPacking_Click(object sender, EventArgs e)
{
Session["OrderID"] = dvOrder.SelectedValue;

if (!string.IsNullOrEmpty(Session["OrderID"] as string))
{
if (!string.IsNullOrEmpty(Session["Shipped"] as string))
{
Response.Redirect("~/PackageManagement/Packing2.aspx");
}
else
{
ShippingError.Visible = true;
}
}

else
{
lblError.Visible = true;
}
}

Make sure each time databound you have to clear session values, for eg assign String.Empty in Session variable




 



Thank you! That worked (although I switched it to being empty).


Here's the code:



protected void Page_Load(object sender, EventArgs e)
{
lblError.Visible = false;
ShippingError.Visible = false;
CanceledError.Visible = false;
dvAddress.Visible = false;
dvCustomer.Visible = false;

}
protected void btnPacking_Click(object sender, EventArgs e)
{
Session["OrderID"] = dvOrder.SelectedValue;

if (Session["OrderID"] != null)
{
if (string.IsNullOrEmpty(Session["Shipped"] as string))
{
ShippingError.Visible = false;
Response.Redirect("~/PackageManagement/Packing2.aspx");
}
else
{
ShippingError.Visible = true;
}
}

else
{
lblError.Visible = true;
}
}

protected void dvOrder_DataBound(object sender, EventArgs e)
{
Session["Address1"] = null;
Session["Shipped"] = null;

if (dvOrder.SelectedValue != null)
{
Label AddressID = dvOrder.FindControl("lblAddressID") as Label;
Address.Text = AddressID.Text;
Session["Address1"] = AddressID.Text;

if (dvOrder.CurrentMode == DetailsViewMode.ReadOnly)
{
Label Shipped = dvOrder.FindControl("lblShipped") as Label;

if (Shipped != null)
{
Session["Shipped"] = Shipped.Text;
}
}
dvAddress.Visible = true;
dvAddress.DataBind();
}
else
{
dvAddress.Visible = false;
}

}







[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] Line up drop down menu items?


Hi,


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


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

End While



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


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


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

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


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

(Warning : This is old code)







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


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

and


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

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


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

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







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


               JOHNSON |                    AJITA |                     BEAR |                       DE |                197013036


               JOHNSON-Smith |                    AJITA |                     BEAR |                       DE |                197013036


 


[RESOLVED] Make DataCell Content link and open that link in a new window


Hi,


I have already made datagrid cell content link and open that link in a new window, but the problem is that the parent window content disappears and only "[object]" is written on the parent page after click on the link. I want that the Parent page must remains
there and when i click on the link the it opens in a new window as popup.


I have tried the following code


   runat="server"/>


Please correct me if any mistake or tell me some alternate way to do this


Thanks & Regards


Muhammad Arsalan Akhtar



Simply set target="_blank" and use DataNavigateUrlFormatString


    DataNavigateUrlFormatString="LoadBalance.aspx?EmbossLine={0}"
DataTextField="vchrEmbossLine" HeaderText="Emboss Line" Target="_blank" />





your code modify: -



Target="_blank"  runat="server"/>



I have tried this earlier but this will open a new tab, I want to open it as a popup in new window


Thanks for reply ,


plz help me 


Regards 


Muhammad Arsalan Akhtar




Target="_blank"  runat="server"/>


Except hyperlink use anchor tag



adfadfsa


It will work


hyper link only navigate in other tab so best use is that as tag


& you want to use server side you can use make set attribute as
runat="server" id="anchor1"




ars88


if using


'<%#Eval("FieldNameInDataBase")%>'


if link button using



 




Thanks buddy


Tell me one thing that can i use  <%#Eval("FieldNameindatabase")%> in window.open function


Plz reply






Dear,


 


of course you can use like


window.open('<%#Eval("FieldNameindatabase")%>')



SomeOne please help how to bind eval in window.open


Regards 


Muhammad Arsalan Akhtar



Use LinkButton



Set OnClientClick property from RowDataBound Event


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = e.Row.FindControl("LinkButton1") as LinkButton;
string vchrEmbossLine=Convert.ToString(DataBinder.Eval(e.Row.DataItem,"vchrEmbossLine"));
lb.OnClientClick = string.Format("window.open('LoadBalance.aspx?EmbossLine={0}',null,'width=800,height=800');", vchrEmbossLine);
}
}









Thanks every one for reply


Regards 


Muhammad Arsalan Akhtar


[RESOLVED] Can I have different SelectMethods for the same DataSource


I have a DataSource that is bound to my gridview. There is a SelectMethod for this DataSource that calls a stored proc and populates this gridview.


I added a dropdown to filter the gridview. After filtering, I need to repopulate the gridview. Can I create a brand new stored proc based on the selectedValue from the dropdown and call this proc from a method and use this new method as SelectMethod for
the same DataSource? so I can repopulate the gridview based on filtering.


My problem is that when I added filtering, it broke sorting. I was using a DataSource to filter but in order for column sorting to take affect, I was told that I have to use DataSourceID (not DataSource) since the column sorting has been built into the program.
When I was using DataSource, I had to set DataSourceID to null (since I can't use both DataSource and DataSourceID), which fixed my filtering problem but broke column sorting in the gridview. I have to use DataSourceID in order for the column sorting to work.


Hope that makes sense. Coming from an MVC background, this really gets me.....


Thanks,

AM



Use same select method. Manipulate the parameter, query, stored procedure to filter data.

I created a new stored proc, a new select method and attached it to the same ObjectDataSource.


It is giving me the following error:


ObjectDataSource 'odsActions' could not find a non-generic method 'GetAudit' that has parameters: attID, reqID, plnID, scope.


GetAudit is the original method with parameters reqID, plnID, scope. It populates the gridview on page_load.


I added another method GetAuditLogFiltered with parameters: attID, reqID, plnID, scope.


I am not sure why it is looking for attID as parameter in GetAudit. What am I missing?


string SelectedVal = ddlAuditLogFilter.SelectedValue.ToString();


            if (!(SelectedVal == "-1"))

            {

                odsActions.SelectParameters.Clear();

                odsActions.TypeName = "Wf.Sparc.DAL.DbAccess";

                odsActions.SelectMethod = "GetAuditFiltered";

                odsActions.SelectParameters.Add("attID", SelectedVal.ToString());

                odsActions.SelectParameters.Add("reqID", reqID.ToString());

                odsActions.SelectParameters.Add("plnID", plnID.ToString());

                odsActions.SelectParameters.Add("scope", scope);

                gvActions.DataBind();


                gvActions.Visible = true;

                btnActionsExport.Visible = true;

            }

            else

            {

                odsActions.SelectParameters.Clear();

                odsActions.SelectParameters.Add("reqID", reqID.ToString());

                odsActions.SelectParameters.Add("plnID", plnID.ToString());

                odsActions.SelectParameters.Add("scope", scope);

                odsActions.Select();

            }


            if (gvActions.Rows.Count == 0)

            {

                gvActions.Visible = false;

                btnActionsExport.Visible = false;

            }


 





archnam



It is giving me the following error:


ObjectDataSource 'odsActions' could not find a non-generic method 'GetAudit' that has parameters: attID, reqID, plnID, scope.





Hi,


The error means ObjectDataSource is confused, try the links below for two possible solutions. 


http://kanthu.blogspot.com/2005/10/objectdatasource.html .


http://stackoverflow.com/questions/16641243/asp-net-objectdatasource-could-not-find-a-non-generic-method-that-has-parameters .


Hope it can help you.


Best Regards,

Amy Peng 





do your GetAudit method have those parameters?


[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] 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] 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] Set MSChart AxixX.Minimum To DateTime


Dear All,


I am binding DateTime values to Chart Control. Everything is working fine. But I want set Minimum And Maximum of AxisX to DateTime value. like


Chart1.ChartAreas[0].AxisX.Minimum=DateTime.Now;

All though Minimum accepts only double value. How I achieve this one. Any suggestion is most valueble in for this post.


Thanks in advance.





Hi,


You can use the DateTime.ToOADate which returns double value.


For more information, please try to refer to the following thread:

http://stackoverflow.com/questions/9790831/having-issues-with-plotting-polar-data-on-a-datetime-x-axis.


#DateTime.ToOADate:

http://msdn.microsoft.com/en-us/library/system.datetime.tooadate.aspx


Hope it can help you.


Best Regards,

Amy Peng 


[RESOLVED] calling Checkbox checked Event


I've a repeater and in repeater i've check box list..wheck is generated dynamically.


How i can call check box checked Even


here is code








<%#GetGroupName(Eval("MENU_MODIFIER_GROUP_NAME_TRANSLATION_ID").ToString().Trim())%>
[Free :
<%#GetFreeQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]   [max:

<%#GetMaxQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]






<%-- --%>
runat="server">









Set cbl Autopostback="true"


CheckedChanged event is for CheckBox instead CheckBoxList


CheckBoxList is using SelectedIndexChanged


This sample for CheckBox


    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
RepeaterItem ri = (RepeaterItem)cb.NamingContainer;
HiddenField hdngrpOpid = (HiddenField)ri.FindControl("hdngrpOpid");
int idx = ri.ItemIndex;




}












<%#GetGroupName(Eval("MENU_MODIFIER_GROUP_NAME_TRANSLATION_ID").ToString().Trim())%>
[Free :
<%#GetFreeQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]   [max:

<%#GetMaxQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]






<%-- --%>
runat="server" AutoPostBack="true" onselectedindexchanged="cbxControl_SelectedIndexChanged" >





On Code Behind
protected void cbxControl__SelectedIndexChanged(object sender, EventArgs e)
{

}


[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] [C# net 4] Culture Info


Hello, hope in your help.


I've this code behind and I need display name of month in italian language.


protected void Page_Load(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("it-IT");

SQL = "SELECT ";
SQL = SQL + " DATE_FORMAT( ";
SQL = SQL + " STR_TO_DATE(Month, '%d/%m/%Y'), ";
SQL = SQL + " '%b, %Y' ";
SQL = SQL + ") AS Month, ";
SQL = SQL + " Number ";
SQL = SQL + " FROM ";
SQL = SQL + " tbl_u ";
SQL = SQL + "ORDER BY ";
SQL = SQL + " YEAR ( ";
SQL = SQL + " STR_TO_DATE(Month, '%d/%m/%Y') ";
SQL = SQL + " ) DESC, ";
SQL = SQL + " MONTH ( ";
SQL = SQL + " STR_TO_DATE(Month, '%d/%m/%Y') ";
SQL = SQL + " ) DESC; ";

try
{
OdbcCommand objCmd = new OdbcCommand(SQL, myConnectionString);
objCmd.CommandType = CommandType.Text;
objCmd.CommandText = SQL;
objCmd.Connection = myConnectionString;

myConnectionString.Open();

....

Chart1.Series["Series1"].XValueMember = "Month";

....

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

}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
myConnectionString.Close();
}
}

I add in code behind the:


Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("it-IT");

and in the aspx page:


<%@ Page Language="C#" Culture="it-IT" UICulture="it-IT" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

But the output for the `month` name is always english.


Can you help me?

Thank you.



I use this to display luglio


Label1.Text = DateTime.Now.ToString("MMMM", CultureInfo.GetCultureInfo("it-IT"));

Maybe you need to format the datetime in aspx page instead in sql



thank you, I tried this but I've error:


OdbcDataReader dr = objCmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
MonthYear = dr["Month"].ToString();
ItalianMonthYear = MonthYear.ToString("MMMM", CultureInfo.GetCultureInfo("it-IT"));
}
}
dr.Close();

Compiler Error Message: CS1501: No overload for method 'ToString' takes 2 arguments





I beleive there is better solution than this


OdbcDataReader dr = objCmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
DateTime dt=new DateTime(DateTime.Now.Year,Convert.ToInt32(dr["Month"]),1);
ItalianMonthYear = dt.ToString("MMMM", CultureInfo.GetCultureInfo("it-IT"));
}
}
dr.Close();







thanks a lot


[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 :)