Showing posts with label table. Show all posts
Showing posts with label table. Show all posts

Saturday, March 31, 2012

string vs stringbuilder

What can I better use?

StringBuilder sb =newStringBuilder();

sb.Append("SELECT ");

sb.Append("count(*) ");

sb.Append("FROM ");

sb.Append("table");

Or

query ="SELECT count(*) FROM table";

Look String is immutual object . you can't perform modification operation but in Stringbuilder is New type of Collection Class that provide feasibility to modify and other string operation without losing value


Hi

Strings of type System.String are immutable in .Net. That means any change to a string cause the runtime to create new string and abandon old one.

That happens invisibly, and many programmers might be surprised that following code allocate four new string in memory:

string s;

s = "select "; // "select"

s += " * from "; // "select * from"

s += " tablename"; // "select * from tablename"

Only the last string has a reference, the other two will be disposed of during garbage collection. Avoiding these types of temporary string helps avoid unnecessary garbage collection, which improve performance.

Use StringBuilder class to create dynamic (mutable) strings.

StringBuilder can span multiple statements. The default constructor creates a buffer of 16 bytes long, which grows as needed. You can specify an initial size and a maximum size if you like.

As in your case, if you do not need to break statement in query thanstringworks. Use StringBuilder when you want to span your query in multiple statement.

Hope this helps you.

Regards,

Mustakim Mansuri



If thats the case it better to use String because you did your query is simple BUT if you are trying to DO Insert with multiple values then you can use the StringBuilder to append values...

Just a little Gee-Whiz info as to how much better StringBuilder can be when you are making several concatenations (especially in a loop):

I was building an HTML string in a while(datareader.Read()) loop, and setting a divs InnerHtml equal to that string at the end. I didn't know any better, I never heard of StringBuilder. Then I came across an article about it, so I figured I'd give it a try. In one of my examples, I had about 1000 rows being returned and was making maybe 2 string concatenations within each iteration of the loop. Needless to say, it was running a little slow (between 3-5 seconds each time the user tried to access the page). After replacing straight string concatenations with StringBuilder.Append() statements, the page loaded almost immediately. A few seconds saved was pretty nice, but what further drove the importance home for me was when I remembered that the database connection was open that whole time. Multiply that by several users hitting the site at the same time, and it became very clear.

Wednesday, March 28, 2012

String was not recognized as a valid DateTime Error

I am extracting a DateTime string from a SQL table, and I want to format it. However, when I try to convert the string to a datetime, I get the error:
"String was not recognized as a valid DateTime"
Here is my code:
private string dateFormatting(String theDate)
{
DateTime strDate;
strDate = Convert.ToDateTime(theDate);
strDate = strDate.ToString("M");
return strDate;
}
theDate has the value of "5/11/2005 5:10:25 PM". If I copy-and-paste the string into the code (instead of "theDate"), it compiles properly. However, leaving it in a variable always return the error above.
What might cause this problem?

Thanks

I'm having the same trouble... Can it be a bug?
Regards,
Luis Sim?es


Your variable "strDate" is a DateTime type. You are trying to fill a DateTime variable with a string:

strDate = strDate.ToString("M");
try this:

privatestring dateFormatting(string theDate)

{

DateTime strDate;

strDate = DateTime.Parse(theDate);

string stringDate = strDate.ToString("M");

return stringDate;

}



this may sound like a dumb question, but are you absoulutly sure that the date you paste in is the same date that your code is reciveing, as in have you place a breakpoint in and checked this for sure. One possibility is that the source of your date string has a different culture to the server running the convert.

On a side note, if your function only formats a date then why not only have yout functon accept a date rather then a string? In other words what context is this function performing its role of the conversion, is it from a databind or from a database object?


I'm not sure if it's gonna change anything but.. try to convert like this..
Convert.ToShortDateTime(variable);
anyway... I guess it changes nothing... except that the date will be returned different..
I am not sure if it's gonna change anything.. but.. try to use like this:

Convert.ToShortDateTime(var_name);
I don't know if it will make any difference at all.. I think it wont accutally... I mean.. about this error...

andrew_K wrote:

this may sound like a dumb question, but are you absoulutly sure that the date you paste in is the same date that your code is reciveing, as in have you place a breakpoint in and checked this for sure. One possibility is that the source of your date string has a different culture to the server running the convert.

On a side note, if your function only formats a date then why not only have yout functon accept a date rather then a string? In other words what context is this function performing its role of the conversion, is it from a databind or from a database object?

I am positive that the date I pasted is the same as the date that my code is receiving.

I have the function accept a string because it is called from a databind. I have tried converting the date before passing it to the function, and it returns the same error. I'd post the code, but I am at home now *-)


DevSlick wrote:

Your variable "strDate" is a DateTime type. You are trying to fill a DateTime variable with a string:

strDate = strDate.ToString("M");
try this:

privatestring dateFormatting(string theDate)

{

DateTime strDate;

strDate = DateTime.Parse(theDate);

string stringDate = strDate.ToString("M");

return stringDate;

}



It still returned the same error onstrDate = DateTime.Parse(theDate);
This is very weird.
Weird, it worked for me
This is driving me crazy. Here's the entire code. Maybe the problem is somewhere else. The stored procedure returns two values, the date and an id. Any help would be greatly appreciated!

protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource dsAdmin = new SqlDataSource();
dsAdmin.ConnectionString = "Data Source=(local);Initial Catalog=birdhair;Integrated Security=True";
dsAdmin.SelectCommand = "usp_Admin_ArchiveList";
dsAdmin.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
Parameter sParam1 = new Parameter();
sParam1.Name = "month";
sParam1.Type = TypeCode.Int32;
sParam1.DefaultValue = DateTime.Now.Month.ToString();
dsAdmin.SelectParameters.Add(sParam1);
Parameter sParam2 = new Parameter();
sParam2.Name = "Year";
sParam2.Type = TypeCode.Int32;
sParam2.DefaultValue = DateTime.Now.Year.ToString();
dsAdmin.SelectParameters.Add(sParam2);
DataGrid gridYear = new DataGrid();
gridYear.AutoGenerateColumns = false;
gridYear.DataSource = dsAdmin;
placeholder.Controls.Add(gridYear);
HyperLinkColumn column = new HyperLinkColumn();
column.DataNavigateUrlField = "LogID";
column.DataNavigateUrlFormatString = "edit.aspx?LogID={0}";
column.DataTextField = "LogTimeStamp";
column.DataTextFormatString = dateFormatting("{0}");
gridYear.Columns.Add(column);
gridYear.DataBind();
}
private string dateFormatting(String theDate)
{
DateTime strDate;
String stringDate;
strDate = DateTime.Parse(theDate);
stringDate = strDate.ToString("M");
return stringDate;
}

String was not recognized as a valid DateTime.

I have a Datagrid that I'm trying to use to update a SQL table. The grid
works and I get the EditCommand to work. When I make a change to a
field, I get a date error. I was getting invalid cast error, but I
changed my Update script. All the scripts I found seem to work up to
that point. What am I missing? BTW-Im using c#.

Here is my Update Script, nor the datetime cast within the parameter
assignment:

private void DataGrid1_UpdateCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{

//--retrieve textbox controls from datagrid--//

string iID = e.Item.Cells[1].Text;

string dtDate = e.Item.Cells[3].Text;

string strMeal = e.Item.Cells[4].Text;

string strLodge = e.Item.Cells[5].Text;

//--assign parameters--//

this.sqlCommand1.Parameters.Add("@dotnet.itags.org.TripDate",Convert.ToDateTime(dtDate.ToString()));

this.sqlCommand1.Parameters["@dotnet.itags.org.Param1"].Value = strMeal.ToString();

this.sqlCommand1.Parameters["@dotnet.itags.org.Param2"].Value = strLodge.ToString();

this.sqlCommand1.Parameters["@dotnet.itags.org.id"].Value = iID;

//--execute update query script--//
// this.sqlConnection1.Open();

// this.sqlCommand1.ExecuteNonQuery();

//--deselect row for edting--//

this.DataGrid1.EditItemIndex = -1;

this.DataGrid1.ShowFooter = true;
BindGrid();

//--debugging code--//
Response.Write(Convert.ToDateTime(dtDate.ToString( )));

}

--
hodgesp
----------------------
Posted via http://www.codecomments.com
----------------------Hi hodgesp,

If after you click Edit button, some field become textboxe, in
datagrid_UpdateCommand event, you should get the textbox first. Then retrieve
data:

TextBox txtDtDate = e.Item.Cells[3].Controls[0] as TextBox;
string dtDate = txtDtDate.Text;

HTH

Elton Wang

"hodgesp" wrote:

> I have a Datagrid that I'm trying to use to update a SQL table. The grid
> works and I get the EditCommand to work. When I make a change to a
> field, I get a date error. I was getting invalid cast error, but I
> changed my Update script. All the scripts I found seem to work up to
> that point. What am I missing? BTW-Im using c#.
> Here is my Update Script, nor the datetime cast within the parameter
> assignment:
>
> private void DataGrid1_UpdateCommand(object source,
> System.Web.UI.WebControls.DataGridCommandEventArgs e)
> {
>
> //--retrieve textbox controls from datagrid--//
> string iID = e.Item.Cells[1].Text;
> string dtDate = e.Item.Cells[3].Text;
> string strMeal = e.Item.Cells[4].Text;
> string strLodge = e.Item.Cells[5].Text;
>
> //--assign parameters--//
> this.sqlCommand1.Parameters.Add("@.TripDate",Convert.ToDateTime(dtDate.ToString()));
>
> this.sqlCommand1.Parameters["@.Param1"].Value = strMeal.ToString();
> this.sqlCommand1.Parameters["@.Param2"].Value = strLodge.ToString();
> this.sqlCommand1.Parameters["@.id"].Value = iID;
>
> //--execute update query script--//
> // this.sqlConnection1.Open();
> // this.sqlCommand1.ExecuteNonQuery();
>
> //--deselect row for edting--//
> this.DataGrid1.EditItemIndex = -1;
> this.DataGrid1.ShowFooter = true;
> BindGrid();
>
> //--debugging code--//
> Response.Write(Convert.ToDateTime(dtDate.ToString( )));
> }
>
> --
> hodgesp
> ----------------------
> Posted via http://www.codecomments.com
> ----------------------
>

String was not recognized as a valid DateTime.

I have a Datagrid that I'm trying to use to update a SQL table. The grid wor
ks and I get the EditCommand to work. When I make a change to a field, I ge
t a date error. I was getting invalid cast error, but I changed my Update sc
ript. All the scripts I found seem to work up to that point. What am I missi
ng? BTW-Im using c#.
Here is my Update Script, nor the datetime cast within the parameter assignm
ent:
private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControl
s.DataGridCommandEventArgs e)
{
//--retrieve textbox controls from datagrid--//
string iID = e.Item.Cells[1].Text;
string dtDate = e.Item.Cells[3].Text;
string strMeal = e.Item.Cells[4].Text;
string strLodge = e.Item.Cells[5].Text;
//--assign parameters--//
this.sqlCommand1.Parameters.Add("@dotnet.itags.org.TripDate",Convert.ToDateTime(dtDate.ToStri
ng()));
this.sqlCommand1.Parameters["@dotnet.itags.org.Param1"].Value = strMeal.ToString();
this.sqlCommand1.Parameters["@dotnet.itags.org.Param2"].Value = strLodge.ToString();
this.sqlCommand1.Parameters["@dotnet.itags.org.id"].Value = iID;
//--execute update query script--//
// this.sqlConnection1.Open();
// this.sqlCommand1.ExecuteNonQuery();
//--deselect row for edting--//
this.DataGrid1.EditItemIndex = -1;
this.DataGrid1.ShowFooter = true;
BindGrid();
//--debugging code--//
Response.Write(Convert.ToDateTime(dtDate.ToString()));
}Hi hodgesp,
If after you click Edit button, some field become textboxe, in
datagrid_UpdateCommand event, you should get the textbox first. Then retriev
e
data:
TextBox txtDtDate = e.Item.Cells[3].Controls[0] as TextBox;
string dtDate = txtDtDate.Text;
HTH
Elton Wang
"hodgesp" wrote:

> I have a Datagrid that I'm trying to use to update a SQL table. The grid
> works and I get the EditCommand to work. When I make a change to a
> field, I get a date error. I was getting invalid cast error, but I
> changed my Update script. All the scripts I found seem to work up to
> that point. What am I missing? BTW-Im using c#.
> Here is my Update Script, nor the datetime cast within the parameter
> assignment:
>
> private void DataGrid1_UpdateCommand(object source,
> System.Web.UI.WebControls.DataGridCommandEventArgs e)
> {
>
> //--retrieve textbox controls from datagrid--//
> string iID = e.Item.Cells[1].Text;
> string dtDate = e.Item.Cells[3].Text;
> string strMeal = e.Item.Cells[4].Text;
> string strLodge = e.Item.Cells[5].Text;
>
> //--assign parameters--//
> this.sqlCommand1.Parameters.Add("@.TripDate",Convert.ToDateTime(dtDate.ToSt
ring()));
>
> this.sqlCommand1.Parameters["@.Param1"].Value = strMeal.ToString();
> this.sqlCommand1.Parameters["@.Param2"].Value = strLodge.ToString();
> this.sqlCommand1.Parameters["@.id"].Value = iID;
>
> //--execute update query script--//
> // this.sqlConnection1.Open();
> // this.sqlCommand1.ExecuteNonQuery();
>
> //--deselect row for edting--//
> this.DataGrid1.EditItemIndex = -1;
> this.DataGrid1.ShowFooter = true;
> BindGrid();
>
> //--debugging code--//
> Response.Write(Convert.ToDateTime(dtDate.ToString()));
> }
>
> --
> hodgesp
> ---
> Posted via http://www.codecomments.com
> ---
>

Monday, March 26, 2012

Stringbuilder or table?

Hi

I am just wondering if i need dynamically create a html table, which way will be more efficient?

A. Use stringbuilder. For example, sb.append("<table border=0>""), for(i=0;i<10;i++){sb.append("<tr><td>abc</td></tr>")}, sb.append("</table>")

B. Use table control, t = new table, for(i=0;i<10;i++){tr=new tablerow, td=new tablecell, td.text="abc",tr.cells.add(td),t.rows.add(tr))

Thanks

~Mike


Hi

Honestly, i dont see it makes huge different

But I think B will quicker than A. because all table, row, cell are object. I think use object to create table will be faster than string built up.


Use the following code to test this:

private void RunTest(int count){ Stopwatch watch =new Stopwatch(); watch.Start();for (int i2 = 0; i2 < count; i2++) { Table table =new Table();for (int i = 0; i < 10; i++) { TableRow tr =new TableRow(); TableCell td =new TableCell(); td.Text ="abc"; tr.Cells.Add(td); table.Rows.Add(tr); } } watch.Stop(); Debug.WriteLine(watch.ElapsedMilliseconds); watch.Reset(); watch.Start();for (int i2 = 0; i2 < count; i2++) { StringBuilder sb =new StringBuilder(); sb.Append("<table border=0>");for (int i = 0; i < 10; i++) { sb.Append("<tr><td>abc</td></tr>"); } sb.Append("</table>"); } watch.Stop(); Debug.WriteLine(watch.ElapsedMilliseconds);} 

I did the test with a count of 1500 which should show a difference and let it run 4 times. The outputs are as follows:

22 // Table
4 // StringBuilder


29
5

22
4

26
4

But, as you won't to that 1,500 times, there won't be a lot of difference concerning the performance.


Hi all,

I think the best way is using Table, TableRow and TableCell objects. You can create a table with all cells and rows you want and navigate throw them using their structure. However, if you want to create a simple table that has only two cells or something similar, it's quicker to use StringBuilder object or a string variable.


If the table doesn't need to be a server control, then I think it would be a little more efficient to use a StringBuilder. I?haven't?done?any?tests,?but?writing?out raw?HTML?generally incurs?less?overhead?than?instantiang?controls?for?everything. Any performance difference between the two approaches is going to be negligable though, so personally i'd go for whatever you find the more readable.

A third, and possible better approach would be to put your information into a DataTable and bind it to a GridView, DataList or Repeater.
I'd say A is going to be slightly more efficient but as already pointed out it'll be negligible. I personally like the markup in my code to be neat when viewed so B would probably better achieve that, even if its only for me debugging its output when it goes skewey.

Saturday, March 24, 2012

Stripping out unwanted characters

How can I strip out unwanted characters in a string before updating the
database? For instance, in names & addresses in our client table, we want
only letters and numbers, no punctuation. Is there a way to do this?HI,

Use regular expression to remove unwanted characters and then send the
string to database. Here is a sample code to remove non-alphanumerical
characters from a string.

hoep this will help you...

public static void Main()

{

/*Reg expression to find non-alphanumeric characters*/

string pattern = @."[^A-Za-z0-9]";

/*include System.Text.RegularExpressions name space*/

Regex rgx = new Regex(pattern);

string inputStr = "ab$!Cd&%$gf!";

/*Replace non-alphanumeric characters with space*/

string outputStr = rgx.Replace(inputStr, " ");

Console.WriteLine("Output string:"+ outputStr);

}

Cheers
Vinu

"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?
Function StripUnwantedChars(ByVal StringToStrip AsString) AsString
Dim stripped AsString
If StringToStrip <> "" Then
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)
Return stripped
Else
Return ""
EndIf
EndFunction

Note : insert all the characters you want to strip inside the quotes.

For example, instead of :
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)

use :
stripped = Regex.Replace(StringToStrip, "<!#(.|\n)+?>", String.Empty)

Juan T. Llibre, asp.net MVP
aspnetfaq.com : http://www.aspnetfaq.com/
asp.net faq : http://asp.net.do/faq/
foros de asp.net, en espaol : http://asp.net.do/foros/
===================================
"et" <eagletender2001@.yahoo.com> wrote in message news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the database? For instance,
> in names & addresses in our client table, we want only letters and numbers, no punctuation. Is
> there a way to do this?
Thanks, everyone, that's exactly what I was looking for.

"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?

Stripping out unwanted characters

How can I strip out unwanted characters in a string before updating the
database? For instance, in names & addresses in our client table, we want
only letters and numbers, no punctuation. Is there a way to do this?HI,
Use regular expression to remove unwanted characters and then send the
string to database. Here is a sample code to remove non-alphanumerical
characters from a string.
hoep this will help you...
public static void Main()
{
/*Reg expression to find non-alphanumeric characters*/
string pattern = @."[^A-Za-z0-9]";
/*include System.Text.RegularExpressions name space*/
Regex rgx = new Regex(pattern);
string inputStr = "ab$!Cd&%$gf!";
/*Replace non-alphanumeric characters with space*/
string outputStr = rgx.Replace(inputStr, " ");
Console.WriteLine("Output string:"+ outputStr);
}
Cheers
Vinu
"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?
>
Function StripUnwantedChars(ByVal StringToStrip AsString) AsString
Dim stripped AsString
If StringToStrip <> "" Then
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)
Return stripped
Else
Return ""
EndIf
EndFunction
Note : insert all the characters you want to strip inside the quotes.
For example, instead of :
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)
use :
stripped = Regex.Replace(StringToStrip, "<!#(.|\n)+?>", String.Empty)
Juan T. Llibre, asp.net MVP
aspnetfaq.com : http://www.aspnetfaq.com/
asp.net faq : http://asp.net.do/faq/
foros de asp.net, en espaol : http://asp.net.do/foros/
===================================
"et" <eagletender2001@.yahoo.com> wrote in message news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl
..
> How can I strip out unwanted characters in a string before updating the da
tabase? For instance,
> in names & addresses in our client table, we want only letters and numbers
, no punctuation. Is
> there a way to do this?
>
Thanks, everyone, that's exactly what I was looking for.
"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?
>

Tuesday, March 13, 2012

Stuck Passing a DataList to a User Component

Hello,

Stuck on this one: I have User Component that is the main content table on my web page. It simply serves as a table with decorative border and header. All content (mostly text) is placed inside this User Component on each of my web pages by accessing the UserControl's properties.

However, now I have a web page with a DataList control, and would love to place this control inside my UserControl, but am stuck.

In my previous pages, I access the UserControl's strContent property that sets the cell.text property to the text coming from my dbase, but once again, is it somehow possible to put my DataList inside this Cell or something similar.

Thanks again,
JohnHad the same problem, here's my solution:


<DefaultProperty("Title"), ParseChildrenAttribute(False), ToolboxData("<{0}:WindowPanel runat=server></{0}:WindowPanel>")> Public Class WindowPanel
Inherits System.Web.UI.WebControls.WebControl

Dim _title As String
Dim _cssclass As String
Dim _width As System.Web.UI.WebControls.Unit

<Bindable(True), Category("Appearance"), DefaultValue("")> Property [Title]() As String
Get
Return _title
End Get

Set(ByVal Value As String)
_title = Value
End Set
End Property

<Bindable(True), Category("Appearance"), DefaultValue("")> Overrides Property [CSSClass]() As String
Get
Return _cssclass
End Get

Set(ByVal Value As String)
_cssclass = Value
End Set
End Property
<Bindable(True), Category("Appearance"), DefaultValue("")> Overrides Property [Width]() As System.Web.UI.WebControls.Unit
Get
Return _width
End Get

Set(ByVal Value As System.Web.UI.WebControls.Unit)
_width = Value
End Set
End Property

Protected Overrides Sub Render(ByVal output As System.Web.UI.HtmlTextWriter)
output.Write("<table border=""0"" cellspacing=""0"" cellpadding=""0"" style=""width:" & _width.ToString & ";border: 1px solid;border-collapse:collapse;"" class=""" & _cssclass & """>" & vbCrLf & _
" <tr>" & vbCrLf & _
" <td style=""padding: 3px; border: 1px solid;"" class=""" & _cssclass & """>" & _title & "</td>" & vbCrLf & _
" </tr>" & vbCrLf & _
" <tr>" & vbCrLf & _
" <td style=""padding: 3px;"">" & vbCrLf)
Me.RenderContents(output)
output.Write(" </td>" & vbCrLf & _
" </tr>" & vbCrLf & _
"</table>")
End Sub

End Class

The important thing to remember is the "ParseChildrenAttribute(False)" Statement to be able to include other controls within this custom control.