Showing posts with label text. Show all posts
Showing posts with label text. Show all posts

Saturday, March 31, 2012

Trim fields in Text File

Hi

I have a text file with 116 fields separated by commas. How would I open the text file and trim all white spaces from each field and then close file?

Thanks

You can Use String.Split function to get array of all string with whitespace than trim that string and Use String.Join function to get comma seperated string

than store it in file


Even simpler would be to run a regex replace on your textfile after readingit.

Regex.Replace(strInput, "\s+", " ")

trim large text

Hi! I have a function that trim large text, but the problem is that it cuts off the last word, so it's not making sense. Is there a function that trim large text in a nice way, making sure the last word is preserved. Thanks for any tip!

Can you just use Trim(myString) ?


You could also use Regular expressions :

using System.Text.RegularExpressions;

private string RemoveSpaces(string str)
{
string result = "";
Regex regulEx = new Regex(@."[\s]+");
result = regulEx.Replace(str," ");
return result;
}

Original code :Laxshmi

HTH,
Suprotim Agarwal

--
http://www.dotnetcurry.com
--



I probably didn't explain what I am doing. If I have a large text to pull from the database and I 'd like just a small portion to be displayed in gridview cell, I am uisng:

Substring(0,Math.Min(100, Eval("Bulletin").ToString().Length)) but this cuts off any last words.


Thank you for the reply! I am looking to shorten text (pulled out of the database)for display in gridview.

Cheers!


:)

Here you go. Even though this is asp code, you will get the idea

http://www.codeproject.com/asp/textpreview.asp

HTH,
Suprotim Agarwal

--
http://www.dotnetcurry.com
--


James,

if I understand you right then you're saying that you want the last word within the 100 character max limit to be preserved and to not be chopped in two, right? Here's a bit of code that might accomplish it for you if that is what you're looking for. It just involves string manipulations is all.

string myStr ="This string should be cut off at the 25th character, and preserve the final word.";string myStr25 = myStr.Substring(0, 25);int lastIdx = myStr25.LastIndexOf(" ");string finalStr = myStr25.Substring(0, lastIdx);

Let me know if you need help from there, but you should be able to adapt it to your need.


If you don't want to cut off words, just trim to the last index of a space.

string text = Eval("Bulletin").ToString();

if (text.Length > 100)

{

text = text.Substring(0, 100);

text = text.Substring(0, text.LastIndexOf(' ') + 1);

}


or how about trying this :

<ItemTemplate>
<%# Eval("Bulletin").ToString().Substring(0, 20) + "..." %>
</ItemTemplate>

Just make sure that all the strings are above 20 characters.

Edit : This code would probably cut off the last words. I do not have my visual studio with me, but what you can do is use this code with the suggestion posted by other members to get your solution.

HTH,
Suprotim Agarwal

--
http://www.dotnetcurry.com
--


I did this but it gave me 95 instead of my text:

<%# Eval("Bulletin").ToString().Substring(0,100).LastIndexOf(" ")%>

I am doing it in the aspx, makes it harder for me.


This is my datalist:

<asp:DataListID="dlBulletins"runat="server">

<ItemTemplate>

<strong><%# Eval("DisplayName")%></strong>

<br/>

<%#formatDate((DateTime)Eval("Bulletin_Date"))%><br/>

<%# Eval("Bulletin").ToString().Substring(0,Math.Min(100, Eval("Bulletin").ToString().Length)) %>

</ItemTemplate>

How can I use the string text in datalist template?

Cheers!

<separatorTemplate><hrnoshade="noshade"size="1"/>

</separatorTemplate>

</asp:DataList></p>


I am using this but it's only returning the first letter!!

<%# Eval("Bulletin").ToString().Substring(0,100).Substring(0,Eval("Bulletin").ToString().LastIndexOf(' ')) %>


It sounds like it's impossible to do this in the datalist!


Thanks friend!! I don't know what i was thinking, I made a function in the code behind called trimtext, then used it in the aspx. Work great now!

Cheers!

Trim String

Hi

I want to trim the end of a string placed on my page.

I want to make it so that even if the text is 100 char long it will only display the first 15 characters.

Is this correct, i cant seem to make it work.

Regards
Ant

<%#Container.DataItem("OutboundCarrierName").ToString.Trim("15") %>

use Substring function in place of this:

<%#Container.DataItem("OutboundCarrierName").ToString().Substring(0,15) %>

thanks


Perfect, that works.

Trimming data in dropdownlist from sqldatareader

When I databind a value/text combination from an
sqldatareader to a dropdownlist, the trailing spaces are
getting included in the dropdownlist. I can RTRIM from
within the SQL to fix this problem, but I am wondering if
there is a more elegant solution to trim all the
text/value combinations in a dropdownlist.Hi William

To my knowledge, there is not an elegant way from dropdownlist side. One
clumsy way I can think of is to populate a new collection or arraylist that
contains the data fields to be bound to the dropwodnlist. While populating
this new collection or arraylist we can trim the data accordingly.

Please let me know if it makes sense.

Best regards,

Jacob Yang
Microsoft Online Partner Support
Get Secure! C www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
Yes, that makes sense. Thank you.
>--Original Message--
>Hi William
>To my knowledge, there is not an elegant way from
dropdownlist side. One
>clumsy way I can think of is to populate a new
collection or arraylist that
>contains the data fields to be bound to the
dropwodnlist. While populating
>this new collection or arraylist we can trim the data
accordingly.
>Please let me know if it makes sense.
>Best regards,
>Jacob Yang
>Microsoft Online Partner Support
>Get Secure! C www.microsoft.com/security
>This posting is provided "as is" with no warranties and
confers no rights.
>.

Trimming Text for a certian charachter or word

I have a database with unique ID numbers. Each id number has images connected to it.

For Example:

www.mysite.com/images/1/4/778814.jpg

www.mysite.com/images/"T"/"U"IDNUMBer.jpg

As you will see the "T" folder comes from the tens spont of the id number. The "U" folder come from the units spot and the image name is the ID and then I have to add jpg. Now i would never create a database like this but that is what this company is supplying me. My question is how to make asp split the id number up to use in other locations.



Thanks

RustyI can think of 2 options. See which is best for you based on the datatype of the idnumber.
a) You can work with strings and use
Dim unit, tens as String
unit = idnumber.ToString().Chars(idnumber.ToString().Length -1) 'to get units character
tens = idnumber.ToString().Chars(idnumber.ToString().Length -2) 'to get the tens character
b) Work with integers and use mathematical operators Eg:
Dim idnumber As Integer
idnumber = 456789
Dim unit, tens As Integer
unit = idnumber Mod 10 ' Returns 9
tens = (idnumber Mod 100) \ 10 ' Returns 8
Use the Split method to split the string by "/" and then you can use each of the elements of the created Array to grab the numbers.

string fullUrl = "www.mysite.com/images/1/4/778814.jpg";
string[] splitParams = fullUrl.Split('/');

splitParams[0] is "www.mysite.com"
splitParams[1] is "images"
splitParams[2] is "1"
splitParams[3] is "4"
splitParams[4] is "778814.jpg"

HTH

DJ

Wednesday, March 28, 2012

Trimming text returned from db

Hi

In my App I have a datagrid with a template column. In my DB I have a field called "Bio" wich holds user biographies. The idea is that within the datagrid only a small portion of the bio is shown and visitors click onto detail pages to see photgraphs and full information. Is there a way to limit the output from the Bio field to say 100 characters

Thanks

hpYou could limit the size of what you display in your datagrid column for Bio through many ways. One of those is to limit what you fetch from the database using LEFT(Bio,100) in your SQL statement.

You could equally use a bound column. This is what MSDN has to say on that:

"A bound column (BoundColumn element) displays information from one column of a data source. You typically add one bound column to the grid for every data column you want to display. Use bound columns when you want to choose which data columns to display in the grid. Bound columns also allow you to set a variety of properties to specify features such as:

The text, font, and color of the column header and footer.
Column width.
Data format.

Whether the column is read-only (that is, whether it will display an editable control when the row is in edit mode).
For details on creating bound columns in the Visual Studio Web Forms Designer, see Adding Bound Columns to a DataGrid Web Server Control. For details on creating bound columns, see DataGrid Web Server Control."

You should be able to combine both approaches to evolve something nice.
In addition if you need the full bio from the db to use later one (perhaps they can vie the full bio via a link or something), you may want to just limit it on the front end. To do this you could use the ItemDataBound of the datagrid. If the value is stored in a control such as a lable you would use FindControl and then set the value. Something like this...

Label lblTemp = (Label)e.Item.FindControl("lblBio");
if (lblTemp != null)
lblTemp = lblTemp.Text.Substring(1, 100);

May not be completely accurate but it should get you on the right path.
Excellent, Many thanks

trimming text in a datagrid to match column length

I have a messaging application that has a data grid with information like an
email list would have (from, subject, time sent, size) but the subject
could be very long in theory, and then it would word wrap.. the subject is a
variable width column (resizes to fit space) while the others are fixed
size... the problem is that i dont want the text to ever word wrap.. but
truncate the visible subject to match the current cell width... (kinda like
gmail does) how would i go about doing this at runtime on the client's page?
thanks!I guess there are a couple of ways that I can think of to fix this. The fir
st and easiest way could be to only return a certain number of characters fr
om the query of stored procedure. For example:
select substring(subject, 0, 10) from emaillist
that way the query will do all the work.
Now another example could be to do it within the code, for example:
<ItemTemplate>
<%# TrimSubject(DataBinder.Eval(Container.DataItem, "Subject")) %>
</ItemTemplate>
public string TrimSubject(string subject)
{
string retVal = subject;
if(retVal.Length>100)
{
retVal = retVal.Substring(0, 100) + "...";
}
return retVal;
}
Hope those examples help.
Alan Washington
http://www.aewnet.com

> I have a messaging application that has a data grid with information like
an
> email list would have (from, subject, time sent, size) but the subject
> could be very long in theory, and then it would word wrap.. the subject is
a
> variable width column (resizes to fit space) while the others are fixed
> size... the problem is that i dont want the text to ever word wrap.. but
> truncate the visible subject to match the current cell width... (kinda lik
e
> gmail does) how would i go about doing this at runtime on the client's pag
e?
> thanks!
>
>
User submitted from AEWNET (http://www.aewnet.com/)
You can use GDI+ to do this. Here's some quick/dirty code I wrote to do
this. Hope this helps!
Joel Cade, MCSD
Fig Tree Solutions, LLC
http://www.figtreesolutions.com
Imports System.Drawing
Public Function MeasureString(ByVal Value As String, ByVal Font As
Drawing.Font) As SizeF
' Set up string.
Dim oBitMap As New Bitmap(1, 1)
Dim oGraphics As Graphics = Graphics.FromImage(oBitMap)
' Measure string.
Dim Size As New SizeF
Size = oGraphics.MeasureString(Value, Font)
Return Size
End Function
Public Function GetTrimmedString(ByVal Value As String, ByVal MaxSizeF
As Single, ByVal Font As Drawing.Font) As String
Dim sReturn As String
If MeasureString(Value, Font).Width < MaxSizeF Then
sReturn = Value
Else
sReturn = Value
Dim i As Integer
Do While MeasureString(Value.Substring(0, Value.Length - i) &
"...", Font).Width > MaxSizeF
i += 1
Loop
sReturn = Value.Substring(0, Value.Length - i) & "..."
End If
Return sReturn
End Function
....
ListBox1.Items.Add(oFormatter.GetTrimmedString("This is a test, THIS IS THE
LONGEST EVER THIS IS THE LONGEST EVER THIS IS THE LONGEST EVER THIS IS THE
LONGEST EVER", 300, New Font(New
System.Drawing.FontFamily(ListBox1.Font.Name), 12, FontStyle.Regular)))
GDI+ on asp.net on the client side? doesn't sound right, because the user
could resize the window thus changing the size of the column the text is in.
"Joel Cade" <joel@.nospam.figtreesolutions.com> wrote in message
news:0F697488-C620-4C51-80EB-803D11AF5D0C@.microsoft.com...
> You can use GDI+ to do this. Here's some quick/dirty code I wrote to do
> this. Hope this helps!
> Joel Cade, MCSD
> Fig Tree Solutions, LLC
> http://www.figtreesolutions.com
> Imports System.Drawing
> Public Function MeasureString(ByVal Value As String, ByVal Font As
> Drawing.Font) As SizeF
> ' Set up string.
> Dim oBitMap As New Bitmap(1, 1)
> Dim oGraphics As Graphics = Graphics.FromImage(oBitMap)
> ' Measure string.
> Dim Size As New SizeF
> Size = oGraphics.MeasureString(Value, Font)
> Return Size
> End Function
> Public Function GetTrimmedString(ByVal Value As String, ByVal MaxSizeF
> As Single, ByVal Font As Drawing.Font) As String
> Dim sReturn As String
> If MeasureString(Value, Font).Width < MaxSizeF Then
> sReturn = Value
> Else
> sReturn = Value
> Dim i As Integer
> Do While MeasureString(Value.Substring(0, Value.Length - i) &
> "...", Font).Width > MaxSizeF
> i += 1
> Loop
> sReturn = Value.Substring(0, Value.Length - i) & "..."
> End If
> Return sReturn
> End Function
> ....
> ListBox1.Items.Add(oFormatter.GetTrimmedString("This is a test, THIS IS
> THE
> LONGEST EVER THIS IS THE LONGEST EVER THIS IS THE LONGEST EVER THIS IS THE
> LONGEST EVER", 300, New Font(New
> System.Drawing.FontFamily(ListBox1.Font.Name), 12, FontStyle.Regular)))
>
Hi Brian,
As for the truncating string values in DataGrid Cell(Table cell), I think
generally we have two means:
1. Truncating the string's length at serverside when we retrieve it from db
or output into the page via code. Just as the other members have suggested.
But this will make the output string's length be a fixed size.
#Creating a Custom DataGridColumn Class, Part 2
http://aspnet.4guysfromrolla.com/ar...100202-1.2.aspx
2. Using css style on the output <table> and the text content in table
cell. There is one css attribute named
"OVERFLOW", it can be applied on <div> or <p> ... and when we set the
"OVERFLOW:Hidden", it will truncat the exceeded content according to the
container element's width.
#overflow Attribute | overflow Property
http://msdn.microsoft.com/library/d...uthor/dhtml/ref
erence/properties/overflow.asp
For example:
<p style="OVERFLOW:hidden;WIDTH:100">
<% Response.Write(new String('d',1000)); %>
</p>
Also, since in our problem, we need to set the datagrid column's width
unfixed, so we also need to make the with of the <p> as a relative size.
After some testing, it seems that we also have to assign the "table-layout
: fixed" css attribute to the DataGrid(<table> ). Here is some demo code on
applying the styles on datagrid:
<asp:DataGrid id="dgStyle" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn DataField="Column1"
HeaderText="Column1"></asp:BoundColumn>
<asp:BoundColumn DataField="Column2"
HeaderText="Column2"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Column3">
<ItemTemplate>
<p style="OVERFLOW:hidden;WIDTH:90%">
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container,
"DataItem.Column3") %>'>
</p>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
=======================
In our code-behind , we can use the following code (in Page_load) to apply
the "table-layout" style on datagrid:
private void Page_Load(object sender, System.EventArgs e)
{
...............
dgStyle.Style["TABLE-LAYOUT"] = "fixed";
}
Hope these help. Thanks.
Regards,
Steven Cheng
Microsoft Online Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
thanks that worked perfectly!
"Steven Cheng[MSFT]" <v-schang@.online.microsoft.com> wrote in message
news:%23bjDCLxtEHA.3696@.cpmsftngxa10.phx.gbl...
> Hi Brian,
> As for the truncating string values in DataGrid Cell(Table cell), I think
> generally we have two means:
> 1. Truncating the string's length at serverside when we retrieve it from
> db
> or output into the page via code. Just as the other members have
> suggested.
> But this will make the output string's length be a fixed size.
> #Creating a Custom DataGridColumn Class, Part 2
> http://aspnet.4guysfromrolla.com/ar...100202-1.2.aspx
> 2. Using css style on the output <table> and the text content in table
> cell. There is one css attribute named
> "OVERFLOW", it can be applied on <div> or <p> ... and when we set the
> "OVERFLOW:Hidden", it will truncat the exceeded content according to the
> container element's width.
> #overflow Attribute | overflow Property
> [url]http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/ref[/ur
l]
> erence/properties/overflow.asp
> For example:
> <p style="OVERFLOW:hidden;WIDTH:100">
> <% Response.Write(new String('d',1000)); %>
> </p>
> Also, since in our problem, we need to set the datagrid column's width
> unfixed, so we also need to make the with of the <p> as a relative size.
> After some testing, it seems that we also have to assign the "table-layout
> : fixed" css attribute to the DataGrid(<table> ). Here is some demo code
> on
> applying the styles on datagrid:
> <asp:DataGrid id="dgStyle" runat="server" AutoGenerateColumns="False">
> <Columns>
> <asp:BoundColumn DataField="Column1"
> HeaderText="Column1"></asp:BoundColumn>
> <asp:BoundColumn DataField="Column2"
> HeaderText="Column2"></asp:BoundColumn>
> <asp:TemplateColumn HeaderText="Column3">
> <ItemTemplate>
> <p style="OVERFLOW:hidden;WIDTH:90%">
> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container,
> "DataItem.Column3") %>'>
> </p>
> </asp:Label>
> </ItemTemplate>
> </asp:TemplateColumn>
> </Columns>
> </asp:DataGrid>
> =======================
> In our code-behind , we can use the following code (in Page_load) to apply
> the "table-layout" style on datagrid:
> private void Page_Load(object sender, System.EventArgs e)
> {
> ...............
> dgStyle.Style["TABLE-LAYOUT"] = "fixed";
> }
>
> Hope these help. Thanks.
> Regards,
> Steven Cheng
> Microsoft Online Support
> Get Secure! www.microsoft.com/security
> (This posting is provided "AS IS", with no warranties, and confers no
> rights.)
>

trimming text in a datagrid to match column length

I have a messaging application that has a data grid with information like an
email list would have (from, subject, time sent, size) but the subject
could be very long in theory, and then it would word wrap.. the subject is a
variable width column (resizes to fit space) while the others are fixed
size... the problem is that i dont want the text to ever word wrap.. but
truncate the visible subject to match the current cell width... (kinda like
gmail does) how would i go about doing this at runtime on the client's page?
thanks!I guess there are a couple of ways that I can think of to fix this. The first and easiest way could be to only return a certain number of characters from the query of stored procedure. For example:

select substring(subject, 0, 10) from emaillist

that way the query will do all the work.

Now another example could be to do it within the code, for example:

<ItemTemplate>
<%# TrimSubject(DataBinder.Eval(Container.DataItem, "Subject")) %>
</ItemTemplate
public string TrimSubject(string subject)
{
string retVal = subject;
if(retVal.Length>100)
{
retVal = retVal.Substring(0, 100) + "...";
}

return retVal;
}

Hope those examples help.

Alan Washington
http://www.aewnet.com

> I have a messaging application that has a data grid with information like an
> email list would have (from, subject, time sent, size) but the subject
> could be very long in theory, and then it would word wrap.. the subject is a
> variable width column (resizes to fit space) while the others are fixed
> size... the problem is that i dont want the text to ever word wrap.. but
> truncate the visible subject to match the current cell width... (kinda like
> gmail does) how would i go about doing this at runtime on the client's page?
> thanks!

User submitted from AEWNET (http://www.aewnet.com/)
You can use GDI+ to do this. Here's some quick/dirty code I wrote to do
this. Hope this helps!

Joel Cade, MCSD
Fig Tree Solutions, LLC
http://www.figtreesolutions.com

Imports System.Drawing

Public Function MeasureString(ByVal Value As String, ByVal Font As
Drawing.Font) As SizeF
' Set up string.
Dim oBitMap As New Bitmap(1, 1)
Dim oGraphics As Graphics = Graphics.FromImage(oBitMap)

' Measure string.
Dim Size As New SizeF
Size = oGraphics.MeasureString(Value, Font)

Return Size
End Function

Public Function GetTrimmedString(ByVal Value As String, ByVal MaxSizeF
As Single, ByVal Font As Drawing.Font) As String
Dim sReturn As String

If MeasureString(Value, Font).Width < MaxSizeF Then
sReturn = Value
Else
sReturn = Value

Dim i As Integer

Do While MeasureString(Value.Substring(0, Value.Length - i) &
"...", Font).Width > MaxSizeF
i += 1
Loop

sReturn = Value.Substring(0, Value.Length - i) & "..."
End If

Return sReturn
End Function

.....

ListBox1.Items.Add(oFormatter.GetTrimmedString("This is a test, THIS IS THE
LONGEST EVER THIS IS THE LONGEST EVER THIS IS THE LONGEST EVER THIS IS THE
LONGEST EVER", 300, New Font(New
System.Drawing.FontFamily(ListBox1.Font.Name), 12, FontStyle.Regular)))
GDI+ on asp.net on the client side? doesn't sound right, because the user
could resize the window thus changing the size of the column the text is in.

"Joel Cade" <joel@.nospam.figtreesolutions.com> wrote in message
news:0F697488-C620-4C51-80EB-803D11AF5D0C@.microsoft.com...
> You can use GDI+ to do this. Here's some quick/dirty code I wrote to do
> this. Hope this helps!
> Joel Cade, MCSD
> Fig Tree Solutions, LLC
> http://www.figtreesolutions.com
> Imports System.Drawing
> Public Function MeasureString(ByVal Value As String, ByVal Font As
> Drawing.Font) As SizeF
> ' Set up string.
> Dim oBitMap As New Bitmap(1, 1)
> Dim oGraphics As Graphics = Graphics.FromImage(oBitMap)
> ' Measure string.
> Dim Size As New SizeF
> Size = oGraphics.MeasureString(Value, Font)
> Return Size
> End Function
> Public Function GetTrimmedString(ByVal Value As String, ByVal MaxSizeF
> As Single, ByVal Font As Drawing.Font) As String
> Dim sReturn As String
> If MeasureString(Value, Font).Width < MaxSizeF Then
> sReturn = Value
> Else
> sReturn = Value
> Dim i As Integer
> Do While MeasureString(Value.Substring(0, Value.Length - i) &
> "...", Font).Width > MaxSizeF
> i += 1
> Loop
> sReturn = Value.Substring(0, Value.Length - i) & "..."
> End If
> Return sReturn
> End Function
> ....
> ListBox1.Items.Add(oFormatter.GetTrimmedString("This is a test, THIS IS
> THE
> LONGEST EVER THIS IS THE LONGEST EVER THIS IS THE LONGEST EVER THIS IS THE
> LONGEST EVER", 300, New Font(New
> System.Drawing.FontFamily(ListBox1.Font.Name), 12, FontStyle.Regular)))
Hi Brian,

As for the truncating string values in DataGrid Cell(Table cell), I think
generally we have two means:

1. Truncating the string's length at serverside when we retrieve it from db
or output into the page via code. Just as the other members have suggested.
But this will make the output string's length be a fixed size.

#Creating a Custom DataGridColumn Class, Part 2
http://aspnet.4guysfromrolla.com/ar...100202-1.2.aspx

2. Using css style on the output <table> and the text content in table
cell. There is one css attribute named
"OVERFLOW", it can be applied on <div> or <p> ... and when we set the
"OVERFLOW:Hidden", it will truncat the exceeded content according to the
container element's width.

#overflow Attribute | overflow Property
http://msdn.microsoft.com/library/d...uthor/dhtml/ref
erence/properties/overflow.asp

For example:

<p style="OVERFLOW:hidden;WIDTH:100">
<% Response.Write(new String('d',1000)); %>
</p
Also, since in our problem, we need to set the datagrid column's width
unfixed, so we also need to make the with of the <p> as a relative size.
After some testing, it seems that we also have to assign the "table-layout
: fixed" css attribute to the DataGrid(<table>). Here is some demo code on
applying the styles on datagrid:

<asp:DataGrid id="dgStyle" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn DataField="Column1"
HeaderText="Column1"></asp:BoundColumn>
<asp:BoundColumn DataField="Column2"
HeaderText="Column2"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Column3">
<ItemTemplate>
<p style="OVERFLOW:hidden;WIDTH:90%">
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container,
"DataItem.Column3") %>'>
</p>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid
=======================
In our code-behind , we can use the following code (in Page_load) to apply
the "table-layout" style on datagrid:

private void Page_Load(object sender, System.EventArgs e)
{
...............

dgStyle.Style["TABLE-LAYOUT"] = "fixed";
}

Hope these help. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
thanks that worked perfectly!

"Steven Cheng[MSFT]" <v-schang@.online.microsoft.com> wrote in message
news:%23bjDCLxtEHA.3696@.cpmsftngxa10.phx.gbl...
> Hi Brian,
> As for the truncating string values in DataGrid Cell(Table cell), I think
> generally we have two means:
> 1. Truncating the string's length at serverside when we retrieve it from
> db
> or output into the page via code. Just as the other members have
> suggested.
> But this will make the output string's length be a fixed size.
> #Creating a Custom DataGridColumn Class, Part 2
> http://aspnet.4guysfromrolla.com/ar...100202-1.2.aspx
> 2. Using css style on the output <table> and the text content in table
> cell. There is one css attribute named
> "OVERFLOW", it can be applied on <div> or <p> ... and when we set the
> "OVERFLOW:Hidden", it will truncat the exceeded content according to the
> container element's width.
> #overflow Attribute | overflow Property
> http://msdn.microsoft.com/library/d...uthor/dhtml/ref
> erence/properties/overflow.asp
> For example:
> <p style="OVERFLOW:hidden;WIDTH:100">
> <% Response.Write(new String('d',1000)); %>
> </p>
> Also, since in our problem, we need to set the datagrid column's width
> unfixed, so we also need to make the with of the <p> as a relative size.
> After some testing, it seems that we also have to assign the "table-layout
> : fixed" css attribute to the DataGrid(<table>). Here is some demo code
> on
> applying the styles on datagrid:
> <asp:DataGrid id="dgStyle" runat="server" AutoGenerateColumns="False">
> <Columns>
> <asp:BoundColumn DataField="Column1"
> HeaderText="Column1"></asp:BoundColumn>
> <asp:BoundColumn DataField="Column2"
> HeaderText="Column2"></asp:BoundColumn>
> <asp:TemplateColumn HeaderText="Column3">
> <ItemTemplate>
> <p style="OVERFLOW:hidden;WIDTH:90%">
> <asp:Label runat="server" Text='<%# DataBinder.Eval(Container,
> "DataItem.Column3") %>'>
> </p>
> </asp:Label>
> </ItemTemplate>
> </asp:TemplateColumn>
> </Columns>
> </asp:DataGrid>
> =======================
> In our code-behind , we can use the following code (in Page_load) to apply
> the "table-layout" style on datagrid:
> private void Page_Load(object sender, System.EventArgs e)
> {
> ...............
> dgStyle.Style["TABLE-LAYOUT"] = "fixed";
> }
>
> Hope these help. Thanks.
> Regards,
> Steven Cheng
> Microsoft Online Support
> Get Secure! www.microsoft.com/security
> (This posting is provided "AS IS", with no warranties, and confers no
> rights.)

Troubble with links in emails

I'm having trouble with links in emails which are sent from my webapp. I'm using System.Net.Mail.SmtpClient and sending mails as plain text. My email body contains a link e.g.http://www.blabla.com/Page.aspx. Some times the dot between blabla and com disappears when the recipient gets the mail.
I was sure this was an issue with the mail client, but apparently many of our customers are experiencing the same problem. I haven't been able to reproduce this problem myself because all my email clients display the links properly, but I have had some of our clients forward the mails to me, and the dot is actually missing. (http://www.blablacom/Page.aspx).
Have any of you guys seen this problem before? And how can I solve it?Are you still using the Beta version??
Yes, this is beta 2. I haven't been able to test it on the final version yet, because I can't reproduce the problem myself and we haven't shipped the new version to our customers yet.
Do you think it will work differently in the final version?
This is an issue that I haven't heard of earlier. I suggest you download the RTM of the .Net Framework and install it (remember to uninstall any beta version before installing if you intend to do this on the same machine). If your problem remains, I suggest you check the original data and code for string manipulation methods which may cause dots to disappear.
We uninstalled Beta 2 and installed RTM. This solved the problem without any changes to the code.

Trouble accessing object before insertion into panel...

Hey everyone,

I have a script that presents the user with a variable number of text boxes (with the ID's "TextBox1", "TextBox2", "TextBox3", etc.) with an image button, and a label asking the user for input. All this is contained in a panel called Panel1. The user puts some text into the boxes and clicks the image button.

When clicked, the image button raises an event that tries and access the text the user entered in the text boxes, assign that text to a label, and display it in Panel2. It will then hide Panel1 and make Panel2 visible. The event generates an error however. I don't understand the error because the code seems straight forward. Here is the code (intTxtCount contains the number of text boxes that the user was presented with):


Public Sub cmdContinueToDeparturePoints(Sender As Object, e As System.Web.UI.ImageClickEventArgs)

Dim i As Integer
For i = 1 To intTxtCount
Dim lblName As New Label()
lblName.ID = "lblName" & i
Dim txtTemp As TextBox
txtTemp = FindControl("TextBox" & i)
lblName.Text = txtTemp.Text '''' Error Generating Line
Panel2.Controls.Add(lblName)
Panel2.Controls.Add(New LiteralControl("<br>"))
Next i

Panel1.Visible = False
Panel2.Visible = True

End Sub


Here is the Error:

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

I think this error is telling me that a control called lblName does not exist physically in my panel, which is true. But if I reference lblName the object (the one I just declared in the sub) shouldn't that be okay? Am I wrong?

Bewildering...Mike :-/1. NullReferenceException is one of the most common programming errors. So it will help to really learn it well. It means that an object that is being dereferenced (the object followed by a period) is 'null' or 'nothing' in VB terms.

In this line, there are two objects being dereferenced:
lblName.Text = txtTemp.Text

lblName is created just above and you dereferenced it when you assigned the ID. So that's not it. txtTemp is the result of FindControl. You are assuming that you will find a control with the ID "TextBox1" (or whatever number 'i' is when this fails). It is returning null at some point.

2. Its likely that you have not recreated the same list of TextBoxes on post back before this loop executes. Also consider that you have a loop maximum in variable that may not reflect the true number of textboxes.

3. If you are going to write code, please consider using a debugger. Single-step through code and review the values of variables, parameters, and properties as things happen. The debugger would stop on the line with the error and let you open a Watch or Local Variable window to see what the values are in lblName and txtTemp.
Peter,

Thanks for such a great response. Yes, I should be using a debugger. If only my company were not so cheap as to let me code without VisualStudio.NET... :-(

Ok. So we have managed to conclude that lblName is not generating the Null Exception. It must be that no value is being assigned to txtTemp.Text from "TextBox1". Your comments in line item number 2 really interest me:

What do you mean by, "you have not recreated the same list of TextBoxes on post back before this loop executes"? I have never had to "recreate" a form for a PostBack event. I don't even know what you mean by that. And as for the maximum loop variable, I am positive this value is correct every time the script runs. The HTML that the server generages clearly shows me the correct number of text boxes, all with the correct names (TextBox1, T...2, T...3, etc.). I don't understand why when this form is submitted and I try to assign the boxes values they are null. Just don't get it.

Here is some code that works fine, this is what I based my current work on:


Sub Page_Load(sender As Object, e As EventArgs)

Dim t As New TextBox()
Dim i As Integer = 1
t.Text = "testtext" & i.ToString()
t.ID = "myTextBox" & i.ToString()
Panel1.Controls.Add(t)
ViewState("i") = i

End Sub

Sub GetTextBoxValueAndAssignToLabel(sender As Object, e As System.EventArgs)

Dim i As Integer
i = ViewState("i")
Dim txtTemp As TextBox
txtTemp = FindControl("myTextBox" & i)
lblTest.Text = txtTemp.Text

End Sub


As you can see, a text box is created that has an ID of "myTextBox1". The number i is passed via ViewState to the event code for the button, and the Text property of the text box is successfully assigned to the label. As far as I can see, the only difference between my code and the code here is that the label control already exists in the form instead of the on-the-fly label creation I used.
Let's start with that darn debugger issue. My sympathies about your situation. The time you waste without a debugger will easily exceed the cost of VS.NET.

In the meantime, did you know that .net framework comes with a debugger? Lookup "DbgClr.exe" at MSDN.Microsoft.com. I have not used it though, since I'm using VS.NET.

On to your code. I'm confused by this, perhaps because you simplified it. I though you had a loop going on. I'm interested in that loop. For example, if you are assigning ViewState("i") = i in each interation of the loop, you are not changing the key passed to ViewState, and thus overwriting the value.

Please do this too: set <@.Page Trace=true >. When the page is first generated, it will show you each control by its ID. FindControl will only search in the "naming container" of that method. In this case, whatever object contains GetTextBoxValueAndAssignToLabel() is the naming container you are searching. If you did Panel1.FindControl, you will be assured of getting values from Panel1. Another thing you can do is simply grab each unique item in Panel1.Controls.
Panel1.Controls(0) - contains TextBox1
Panel1.Controls(1) - contains TextBox2

Monday, March 26, 2012

Trouble displaying Japanese text with aspx

Friends,
I am having trouble displaying Japanese text within a textbox (or
anywhere else) in an aspx page with .net 2.0 framework. Initial
default text in Japanese displays perfectly but when I attempt to
change the text following a button-click event, it displays as junk.
I have tried setting the globalization tag in the web.config file but
that does not help eiter.
<globalization requestEncoding="UTF-8" responseEncoding="UTF-8"
fileEncoding="UTF-8"/>
I should mention that the problem does not happen in my development pc
where I am using the Visual Web Developer 2005 IDE. It happens only
when I deploy the files to the actual IIS webserver on Windows 2000.
Would greatly appreciate any help.
Here's what I have:
1. TestJP.aspx contains:
<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true"
CodeFile="TestJP.aspx.cs" Inherits="TestJP" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test JP</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtJP" runat="server" Height="101px"
Width="374px">Default Japanese Text</asp:TextBox>
<br />
<asp:Button ID="cmdJP" runat="server" Text="Change Text"
OnClick="cmdJP_Click" />
</div>
</form>
</body>
</html>
2. TestJP.aspx.cs contains:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class TestJP : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdJP_Click(object sender, EventArgs e)
{
txtJP.Text = "New Japanese text";
}
}On May 8, 9:16 am, pardesiya <zenst...@.gmail.com> wrote:
> Friends,
> I am having trouble displaying Japanese text within a textbox (or
> anywhere else) in an aspx page with .net 2.0 framework. Initial
> default text in Japanese displays perfectly but when I attempt to
> change the text following a button-click event, it displays as junk.
> I have tried setting the globalization tag in the web.config file but
> that does not help eiter.
> <globalization requestEncoding="UTF-8" responseEncoding="UTF-8"
> fileEncoding="UTF-8"/>
> I should mention that the problem does not happen in my development pc
> where I am using the Visual Web Developer 2005 IDE. It happens only
> when I deploy the files to the actual IIS webserver on Windows 2000.
> Would greatly appreciate any help.
> Here's what I have:
> 1. TestJP.aspx contains:
> <%@. Page Language="C#" AutoEventWireup="true"
> CodeFile="TestJP.aspx.cs" Inherits="TestJP" %>
> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www
.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
> <html xmlns="http://www.w3.org/1999/xhtml" >
> <head runat="server">
> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
> <title>Test JP</title>
> </head>
> <body>
> <form id="form1" runat="server">
> <div>
> <asp:TextBox ID="txtJP" runat="server" Height="101px"
> Width="374px">Default Japanese Text</asp:TextBox>
> <br />
> <asp:Button ID="cmdJP" runat="server" Text="Change Text"
> OnClick="cmdJP_Click" />
> </div>
> </form>
> </body>
> </html>
> 2. TestJP.aspx.cs contains:
> using System;
> using System.Data;
> using System.Configuration;
> using System.Collections;
> using System.Web;
> using System.Web.Security;
> using System.Web.UI;
> using System.Web.UI.WebControls;
> using System.Web.UI.WebControls.WebParts;
> using System.Web.UI.HtmlControls;
> public partial class TestJP : System.Web.UI.Page
> {
> protected void Page_Load(object sender, EventArgs e)
> {
> }
> protected void cmdJP_Click(object sender, EventArgs e)
> {
> txtJP.Text = "New Japanese text";
> }
>
> }- Hide quoted text -
> - Show quoted text -
Go to File - Save .aspx As - point to Save and select Save with
Encoding... What encoding do you use to save the file?
On May 8, 9:30 am, Alexey Smirnov <alexey.smir...@.gmail.com> wrote:
> Go to File - Save .aspx As - point to Save and select Save with
> Encoding... What encoding do you use to save the file... Hide quoted text -
>
Wait... you have to check the encoding for your TestJP.aspx.cs file.
It seems that it saved in a different encoding...
Alexey thanks a lot for your prompt suggestion. That worked!
TestJP.aspx.cs and TestJP.aspx were saved with Shift_JIS. Changed
that to UTF-8 and it works fine!
I have a second question which is related. I query data into a dataset
and display the result in the same text box but it appears junk. Is
there any way I should set the charset of the DataSet? The database is
probably encoded with Unicode.
DataSet dsTables = new DataSet();
dsTables = <code to get data from database>
txtJP.Text = dsTables.Tables[0].Rows[0]["japanese_name"].ToString();
using System.Data.OleDb;
On May 8, 10:32 am, pardesiya <zenst...@.gmail.com> wrote:
> Alexey thanks a lot for your prompt suggestion. That worked!
> TestJP.aspx.cs and TestJP.aspx were saved with Shift_JIS. Changed
> that to UTF-8 and it works fine!
> I have a second question which is related. I query data into a dataset
> and display the result in the same text box but it appears junk. Is
> there any way I should set the charset of the DataSet? The database is
> probably encoded with Unicode.
> DataSet dsTables = new DataSet();
> dsTables = <code to get data from database>
> txtJP.Text = dsTables.Tables[0].Rows[0]["japanese_name"].ToString();
Where data came from? Did you do that from your asp.net application?
It seems that the data encoded in other format...
Try to change encoding of your result page, in IE right click,
Encoding - Shift_JIS (or any other)
Thanks Alexey. Yes, I'm getting the data from asp.net application.
But changing the encoding in IE doesnt seem to help. As you mention
maybe the data is encoded differently. Probably I should post this as
a separate thread.
using System.Data.OleDb;
OleDbConnection OledbConn = new OleDbConnection();
OleDbDataAdapter OledbDataAdap = new OleDbDataAdapter();
DataSet OleDbDS = new DataSet();
OledbConn.ConnectionString = <connection string to Sybase
database>;
OledbConn.Open();
OledbDataAdap.SelectCommand = new OleDbCommand("select
japanese_name from ... ", OledbConn);
OledbDataAdap.Fill(OleDbDS);
OledbConn.Close();
return OleDbDS;
On May 8, 11:06 am, pardesiya <zenst...@.gmail.com> wrote:
> Thanks Alexey. Yes, I'm getting the data from asp.net application.
> But changing the encoding in IE doesnt seem to help. As you mention
> maybe the data is encoded differently. Probably I should post this as
> a separate thread.
> using System.Data.OleDb;
> OleDbConnection OledbConn = new OleDbConnection();
> OleDbDataAdapter OledbDataAdap = new OleDbDataAdapter();
> DataSet OleDbDS = new DataSet();
> OledbConn.ConnectionString = <connection string to Sybase
> database>;
> OledbConn.Open();
> OledbDataAdap.SelectCommand = new OleDbCommand("select
> japanese_name from ... ", OledbConn);
> OledbDataAdap.Fill(OleDbDS);
> OledbConn.Close();
> return OleDbDS;
Sorry, I think I was not clear. I'm interesting in the code which
stored the data in the database. I guess, you have a kind of web form
with fields and submit button which fires the code-behind action. This
form has to be in UTF encoded
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
not sure about a code (want to see it first)
and your database should support that encoding.
Actually, if you browse the database using a shell, do you see the
correct characters? Are you able to insert any data in Japanese (using
a shell) and see that text on the website?
Ok I understand what you mean. Actually I am not sure about how the
data is stored in the database. The people who maintain the database
have some kind of tool or database application to insert the data. I
only try to retrieve some data using an oledb connection in my asp.net
form.
But I am able to browse the database using Microsoft Query and see the
Japanese data correctly. I can even download the correct data into
Excel. I dont have permission to insert data so cannot check that
part.
On May 8, 11:50 am, pardesiya <zenst...@.gmail.com> wrote:
> Ok I understand what you mean. Actually I am not sure about how the
> data is stored in the database. The people who maintain the database
> have some kind of tool or database application to insert the data. I
> only try to retrieve some data using an oledb connection in my asp.net
> form.
> But I am able to browse the database using Microsoft Query and see the
> Japanese data correctly. I can even download the correct data into
> Excel. I dont have permission to insert data so cannot check that
> part.
1. Check the existing output. Maybe it will give you idea about
encoding.
2. Try to encode
System.Text.Encoding en1 = System.Text.Encoding.Unicode;
System.Text.Encoding en2 = System.Text.Encoding.UTF8;
txtJP.Text = en2.GetString(en1.GetBytes(dsTables.Tables[0].Rows[0]
["japanese_name"].ToString()));
or
System.Text.Encoding en1 =
System.Text.Encoding.Encoding.GetEncoding("Shift_JIS"); // or any
other standard JP-encoding
System.Text.Encoding en2 = System.Text.Encoding.UTF8;
txtJP.Text = en2.GetString(en1.GetBytes(dsTables.Tables[0].Rows[0]
["japanese_name"].ToString()));
3. Check code page of your database
4. Contact db-developers :-)

Trouble Performing An HTTP POST

Hi there. I'm having trouble with an HTTP Post in my code behind. Can
anyone help?

Here's my code:

string data = "&fields_fname = " + txtFirstName.Text + "&fields_lname="
+ txtLastName.Text;
string url = "http://localhost/app/default.asp";

WebRequest objWebRequest = WebRequest.Create(url);
objWebRequest.Method = "POST";
objWebRequest.ContentType = "application/x-www-form-urlencoded";

byte[] bytes = System.Text.Encoding.ASCII.GetBytes (data);
objWebRequest.ContentLength = bytes.Length;

Stream outputStream = objWebRequest.GetRequestStream();
outputStream.Write (bytes, 0, bytes.Length);
outputStream.Close ();Whats the trouble your having with it?

The first thing I notice is that you start your data with a &, you dont
need one in front.

Other than that, whats the problem?

Sean

rh120...@.gmail.com wrote:

Quote:

Originally Posted by

Hi there. I'm having trouble with an HTTP Post in my code behind. Can
anyone help?
>
Here's my code:
>
>
string data = "&fields_fname = " + txtFirstName.Text + "&fields_lname="
+ txtLastName.Text;
string url = "http://localhost/app/default.asp";
>
WebRequest objWebRequest = WebRequest.Create(url);
objWebRequest.Method = "POST";
objWebRequest.ContentType = "application/x-www-form-urlencoded";
>
byte[] bytes = System.Text.Encoding.ASCII.GetBytes (data);
objWebRequest.ContentLength = bytes.Length;
>
Stream outputStream = objWebRequest.GetRequestStream();
outputStream.Write (bytes, 0, bytes.Length);
outputStream.Close ();

Trouble posting to Database from Drop Down List and Text box

I'm having real trouble posting from the webpage back to a database. This is supposed to be one of the easiest things to do in ASP.NET. I've checked viewstate on all of the controls and at the page level and all are set to true.

When I type in some text information, no other characters but plane text, and hit the submit button the text disappears from the box, the drop downlist returns to default, the subroutine runs and an empty space is submitted to the database.

I've verified that the procedure in my namespace is running correctly by allowing the subroutine in the code behind to trigger the SPROC in the namespace. The 'hardcoded' values are inserted into the database.

I also placed a label.text = textbox.text into the subroutine and it is always set to a blank. Even on page intialization. None the less, I wanted to see if running the subroutine would place text inside of the label and it didn't. If I hard code the label, such as label.text = "stanley" then stanley appears when you click the link button. Thus, I'm sure that the subroutine is running, its appears that the text in the text box is being lost when the page makes a round trip.

Any ideas?

SethLet's see your code.
Be sure that you are wrapping any code that initializes the values textbox and dropdownlist in your Page_Load with a check for IsPostBack:


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
'Initialize initial values of textbox and dropdownlist here
End If
End Sub

If you don't, each time the page postsback, the controls will be reset back to their initial state, probably blank for the textbox and no selected item for the drop down list. Remember that when the page posts back, Page_Load will run BEFORE any of the web control event handlers.

Saturday, March 24, 2012

Trouble saving html in a string variable

I'm trying to allow a user to enter html text into a textBox (FreeTextBox) but am getting an error upon submitting:

A potentially dangerous Request.Form value was detected from the client (noteTextBox="<H2><FONT size=6>asd...").
Description:Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Exception Details:System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (noteTextBox="<H2><FONT size=6>asd...").

Anybody know how to deal with this while still allowing me to save the html?

<%@. Page...... ValidateRequest="false".....%>


I think the reason for this error was that someone could enter a <script> tag in your textbox with javascript code, and then if you grab that value from the form and display directly it on another page, the code in the <script> tag would be executed on your user's computer... this could be potentially bad. i usually turn the error off though, like the previous poster. If you HtmlEncode() anything that you display that ultimately came from the user, it should be ok to turn it off.


How do I HtmlEncode() this text?


dim myText as String = Server.HtmlEncode(yourTextbox.Text)

trouble setting text values in custom controls

hi,
i have created a simple custom control with a simple text label on it. This is the ascx code for my control.
I have removed the compiler generated stuff to save space.
It has a simple text label on it - called lbBanner

PublicClass BannerAndGrid 'this is my custom control class
Inherits System.Web.UI.UserControl

ProtectedWithEvents lbBannerAs System.Web.UI.WebControls.Label 'this is my text label on my custom control

PrivateSub Page_Init(ByVal senderAs System.Object,ByVal eAs System.EventArgs)HandlesMyBase.Init
InitializeComponent()
EndSub

PublicProperty Banner() ' this property should get/set the text field on the text labale on my custom control
Get
Return lbBanner.Text
EndGet
Set(ByVal Value)
lbBanner.Text = Value'WHEN I DO THIS I GET AN ERROR SAYING THAT THE OBJECT IS NOT SET TO AN INSTANCE OF THE OBJECT
EndSet
EndProperty

EndClass
I instantiate my control thus:
dim aControl as BannerAndGrid
aControl = new BannerAndGrid
aControl.Banner = "abc" ---see above property Banner--when I do this I get a reference error - WHY ?
I cannot see why I cannot set values within my control by using properties to set/get values.
Am I doing something wrong or is there a better way?
All help greatly appreciated.
Cheers.

When you are dynamically creating UserControls you should use LoadControl, rather than instantiating it in the way you are doing. For example:
dim aControl as BannerAndGrid
aControl = CType(LoadControl("/location/of/BannerAndGrid.ascx"), BannerAndGrid)
aControl.Banner = "abc" 'This will work.


Thanks Steven - the above solution worked perfectly.

Cheers

Chas (Canterbury,UK)

Trouble updating

I have a Access database with 2 text fields. I'm reading one field into a text box, changing the value in the textbox and attempting to update the database with the new value. The page loads fine with the correct value in the textbox, but I'm getting a error on the Update statement. Below is the code. Any suggestions?

Sub LoadInventory()
Connect()
Dim strQuery As String = "SELECT Type, Number FROM Inventory WHERE type = 'squares'"

Dim dbComm As New OLEDBCommand(strQuery, objConnection)
Dim reader As OLEDBDataReader = dbComm.ExecuteReader()

reader.Read()
txtAmount.Text = reader.GetString(1)

reader.Close()
Disconnect()
End Sub

Sub btnChange_Click(ByVal Sender As Object, ByVal E As EventArgs)
UpdateInventory()
LoadInventory()
End Sub

Private Sub UpdateInventory()
Dim strSQL As String = "UPDATE Inventory SET Number = " & txtAmount.Text & " WHERE Type = 'squares'"
Connect()
Dim dbComm As New OLEDBCommand(strSQL, objConnection)
dbComm.ExecuteNonQuery()
Disconnect()
End Subinstead of

Dim strSQL As String = "UPDATE Inventory SET Number = " & txtAmount.Text & " WHERE Type = 'squares'"

try this
Dim strSQL As String = "UPDATE Inventory SET Number = " & Convert.ToInt32(txtAmount.Text) & " WHERE Type = 'squares'"

Jeff
Jeff,

Thanks for your reply. That however didn't work. Could it be the way I have my access database setup?

Jeremy
Jeff,

Does it work when you try putting in a static value for txtAmount.Text such as this:

"UPDATE Inventory SET Number =1 WHERE Type='squares'"

If it does work like that, then try doing this:


Try
Dim dbComm As New OLEDBCommand(strSQL, objConnection)
dbComm.ExecuteNonQuery()
Catch dbException As Exception
Response.Write(dbException.ToString())
End Try

Tell us what the exception is. Besides, it is always good practice anyway to put database queries inside a try statement - there are just way too many things that could go wrong to not catch those errors.

Aaron

Trouble with ASP.net validation

I built this website. It works and the validation works. I want in addition to the star to appear the label on the left for the text to turn red.

www.nodebt.com

The old website which i did too in classic asp http://www.nodebt.com/form.asp - it works as i want it.I ran both pages. The old style changed the label to read and did not show the '*'.

In Microsoft's validators, you have limited formatting options. You can hide the '*' by setting the Display property to "none". You cannot automatically change the color of another field's label. You'd have to write code on the server side that detected if each validator IsValid property is false and change the style of the associated label. If you use the client-side validation (a benefit of ASP.NET), there isn't a clean hack to help you.

I wrote my productProfessional Validation And More for ASP.NET to solve these formatting limitations. I encourage you to review my site to learn what I've done and all the other limitations of Microsoft's validators so you can determine the best course of action. In my product, you can indicate the label and have it change to a different style when the error is shown. It works fully within client-side validation.

trouble with click triggered events

i have a datagrid with delete text links.

I want a confirmation to be made after clicking delete once.


protected void DataGrid1_Del(object sender, DataGridCommandEventArgs e)
{
// make sure things that are invisible stay that way. Also make sure all fields are still blank.
ClearForm();
DataGrid1.EditItemIndex= -1;

MsgLabel.Text = "Are you sure you want to delete the record?";
MsgLabel.Visible = true;
CancelBtn.Visible = true;
DeleteBtn.Visible = true;

} // end DataGrid1_Del

private void DeleteBtn_Click(object sender, System.EventArgs e)
{
String deleteCmd = "DELETE from Inventory where InvName = @dotnet.itags.org.InvName";

SqlCommand myCommand = new SqlCommand(deleteCmd, sqlConnection1);
myCommand.Parameters.Add(new SqlParameter("@dotnet.itags.org.InvName", SqlDbType.NVarChar, 20));
myCommand.Parameters["@dotnet.itags.org.InvName"].Value = DataGrid1.DataKeys[(int)e.Item.ItemIndex];****

myCommand.Connection.Open();
myCommand.ExecuteNonQuery();

myCommand.Connection.Close();
dataSet11.Clear();
sqlDataAdapter1.Fill(dataSet11);

DataGrid1.DataBind();
}

What this code is SUPPOSED to do is, when the delete event is triggered, it will ask you if you are sure you want to delete the record. Upon clicking either delete or cancel, you will call the corresponding function.

The problem here is that, in my DeleteBtn_Click function, it does not recognize e.Item.ItemIndex, b/c this function e is System.EventArgs, instead of DataGridCommandEventArgs. (line is marked ****)

Does anyone have any suggestions to accomplish what I'm trying to do here?

Thanks,
TomIf I understand correctly, in "DataGrid1_Del()" can you save the "itemindex" in a session object and further use it in "DeleteBtn_Click()"?
Hope this helps
Yugang

_______________________

This posting is provided "AS IS" with no warranties, and confers no rights.
could you direct me to info on sessions? That is outside my "knowledge base." :D
Inside "DataGrid1_Del()" use code to record itemindex:
Session.Add("ItemIndex", e.Item.ItemIndex)

Inside "DeleteBtn_Click" get value from session:
Dim itenIndex As Integer = CInt(Session.Item("ItemIndex"))

For complete introduction, please refer:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconsessionstate.asp

Hope this helps
Yugang
I will check the link you provided, thanks.

Initially, when I modify my code as you suggested, in the:

int itemIndex = CInt(Session.Item("ItemIndex"))

line, Session does not have a definition for "Item." (C#)

Are you sure this is correct? Like I said, I'll be checking that link.
Sorry to provide you with VB Code. For C# the code should be:
int itemIndex = int.Parse(Session["ItemIndex"].ToString())
Thanks
Yugang
cool deal, so what should I use in this line?

myCommand.Parameters["@.InvName"].Value = DataGrid1.DataKeys[(int)e.Item.ItemIndex];

What would I replace e.Item.ItemIndex with?

thanks Yugang!
ooops, as i clicked post, i saw what i was looking at, stupid me. I put

myCommand.Parameters["@.InvName"].Value = DataGrid1.DataKeys[itemIndex];

right?
Yes. Please try it
Thanks
Yugang
worked like a charm, much thanks Yugang!!!

Tom
I would stay away from the Session object (this also goes with Application) object. They have many problems (like thread affinity) which cause scaling problems.

Tuesday, March 13, 2012

Trouble with time

Hi,

I'm importing some data from a text file but I have a field that looks like this

30/12/1899 15:25:00

it is time field from an access DB that when exported shows the date and time (ie date = 0) now I want just the time to put into an SQL Server.

The only thing I can think to do is treat it as a string and cut it up to get '15:25:00' and then to put that into a char field in the DB.

There has to be a better way? can anyone help?

Thanks

Hello, if you are storing your date in a string format you can do this:
// Long Time
string LongTime = DateTime.Now.ToString( "T" );
// => Displays 3:47:37 PM
regards

Thanks that works nicely.
I am glad I was able to help. But watch out, if you intend to do datecomparison, that is not a good solution, its then better to storeDateTime in a DateTime field.
regards

Troubles with INSERT INTO Statement...

hey all, im currently trying to do an insert statement, using textbox's and a variable. the only thing is its inserting txtTextBox.Text into the db instead of the value of that textbox...and i get this error when trying to insert my variable...

Exception Details: System.Data.SqlClient.SqlException: The name 'RndmNum' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.

Source Error:

Line 42: dbQuery = "INSERT INTO table (name, fault_type, fault_location, fault_description, fault_number) VALUES ('txtName.Text', 'txtType.Text', 'txtLocation.Text', 'txtDesc.Text', RndmNum)"
Line 43: dbCommand = New SqlCommand(dbQuery,dbConnection)
Line 44: dbCommand.ExecuteNonQuery()
Line 45: dbConnection.Close
Line 46:

this is my insert statement:

dbQuery = "INSERT INTO table (name, fault_type, fault_location, fault_description, fault_number) VALUES ('txtName.Text', 'txtType.Text', 'txtLocation.Text', 'txtDesc.Text', RndmNum)"

thanks everyone,
JustinYou are sending txtName.Text as a string. Your dbQuery needs to look like this:

dbQuery = "INSERT INTO table (name, fault_type, fault_location, fault_description, fault_number) VALUES ('" & txtName.Text & "', '" & txtType.Text & "', '" & txtLocation.Text & "', '" & txtDesc.Text & "', " & RndmNum & ")"