Monthly Archives: August 2008

ASp.Net 2.0 GridView Delete Button Confirmation pop-up

While using GridView in asp.net pages wants to confirm the deletion form user. To do this we can take him to another page having GUI to confirm and then delete the record on that page.

Instead of doing so much hardwork you can achieve this on the same page with a little bit of extra code.

Workaround

Add a client alert script to the delete button of every row.
In the delete event of GridView delete the record.

Code

==================================================
Page’s Aspx Design File Begins
==================================================
<asp:GridView ID=”gvFaq” runat=”server” AutoGenerateColumns=”False” CellPadding=”4″
ForeColor=”#333333″ GridLines=”None” OnRowDataBound=”gvFaq_RowDataBound” OnRowDeleting=”gvFaq_RowDeleting”>
<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
<Columns>
<asp:BoundField DataField=”slno” HeaderText=”Sl No.” />
<asp:BoundField DataField=”cHeading” HeaderText=”Question” />
<asp:BoundField DataField=”cPosition” HeaderText=”Position” />
<asp:CommandField HeaderText=”Manage” ShowSelectButton=”True” />
<asp:CommandField HeaderText=”Delete” ShowDeleteButton=”True” />
</Columns>
<PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<EditRowStyle BackColor=”#999999″ />
<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
</asp:GridView>
==================================================
Page’s Aspx Design File Ends
==================================================

Database Design FIle

==================================================
Code Behind File Begins
==================================================
1) Import Namespaces
using System.Data.SqlClient;

2) Declare global variables which will be used in page
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = “your database connection string goes here”‘;
String sql = string.Empty;

3) Page Load event
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
fillGridView();
}
}

4) GridView filling method
private void fillGridView()
{

try
{
myConnection = new SqlConnection(connStr);
sql = “select * from tblFaq order by slno desc”;

da = new SqlDataAdapter(sql, myConnection);
ds.Clear();
da.Fill(ds, “tblFaq”);

gvFaq.DataSource = ds.Tables[0];
Page.DataBind();

}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

5) In the RowDataBound event add a java script event to the delete cell.
protected void gvFaq_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[4].Attributes.Add(“onClick”, “return confirm(‘Are you sure you want to delete the record?’);”);
}
}

6) Handle the RowDeleting event to delete the record of current row.

protected void gvFaq_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
myConnection = new SqlConnection(connStr);
myConnection.Open();
sql = “delete from tblFaq where slno = ” + Convert.ToInt32(gvFaq.Rows[e.RowIndex].Cells[0].Text);
SqlCommand oldcom = new SqlCommand(sql, myConnection);
oldcom.ExecuteNonQuery();
myConnection.Close();
fillGridView();
Response.Write(“Record Deleted”);
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}

==================================================
Code Behind File Ends
==================================================
The output will look like this

For Source Code visit http://dotnetcoderoom.blogspot.com/2008/08/aspnet-20-gridview-delete-button.html


Show Message Box in Asp.net

It’s not possible to show an alert message box in asp.net using server side code (like vb.net windows apps, msgbox).

But this can be achieved by generating a client side Java Script code in a server-side event.

Code

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
showMsg(“hey there”, Me)
End Sub

Public Sub showMsg(ByVal sMsg As String, ByVal frm As Web.UI.Page)

Dim sb As New System.Text.StringBuilder
Dim oFormObject As System.Web.UI.Control

sMsg = sMsg.Replace(“‘”, “\'”)
sMsg = sMsg.Replace(Chr(34), “\” & Chr(34))
sMsg = sMsg.Replace(vbCrLf, “\n”)
sMsg = “<script language=javascript>alert(“”” & sMsg & “””)</script>”

sb = New System.Text.StringBuilder
sb.Append(sMsg)

For Each oFormObject In frm.Controls
If TypeOf oFormObject Is HtmlForm Then
Exit For
End If
Next
oFormObject.Controls.AddAt(oFormObject.Controls.Count, New LiteralControl(sb.ToString()))
End Sub

Explanation:

On the button click event i write a JavaScript method to the page, the JavaScript method is displaying the message your pass to the method  showMsg().

Note:
Please don’t pass special characters as the message, as they will conflict with the special characters of JavaScript and message won’t come properly.

For more articles updates and sourcecodes please visit dotnetcoderoom


Remove yellow autocomplete textbox background caused by Google Toolbar in Internet Explorer

Hey guys,

Recently i ran into this problem, some users of my client’s website complaint that in some web forms the name and email fields comes have a yellow background which hinders the readability of the field.

After getting into depth details of the problem I came to knew that it happens only in Internet Explorer having Google Toolbar installed. In Firefox, Opera, Netscape it works fine.

This is a feature of Google Toolbar that it automatically highlights the fields (e.g. name, email etc.) in the yellow background color which facilitate the user to autocomplete the specified field.

Using some server-side and client side tweaks you can restrict the field to become autocomplete but Google Toolbar will still show the yellow background. The Google Toolbar feature overrides nearly all the server-side as well as client-side tweaks for the Name and Email fields.

Workaround:

To avoid the field’s autocomplete:

You can set the AutoCompleteType property in the Html tag of Textbox like:

<asp:TextBox ID=”txtemail” runat=”server” AutoCompleteType=”Disabled” Width=”219px”></asp:TextBox>

Some enumerations for the AutoCompleteType property are :

BusinessCity – City in the business category

BusinessCountryRegion – Country/region in the business category

BusinessFax – Fax number in the business category

BusinessPhone – Phone number in the business category

BusinessState – State in the business category

BusinessStreetAddress – Street address in the business category

BusinessUrl – Web site URL in the business category

BusinessZipCode – ZIP code in the business category

Cellular – Phone number in the mobile-phone category

Company – Business name in the business category

Department – Department in the business category

Disabled – AutoComplete feature is disabled

DisplayName – Name to display in the user category

Email – E-mail in the user category

FirstName – First name in the user category

Gender – Gender in the user category

HomeCity – Home city in the user category

HomeCountryRegion – Home country/region in the user category

HomeFax – Fax number in the user category

Homepage – Web site URL in the user category

HomePhone – Phone number in the user category

HomeState – Home state in the user category

HomeStreetAddress – Home street in the user category

HomeZipCode – ZIP code in the user category

JobTitle – Job title in the user category

LastName – Last name in the user category

MiddleName – Middle name in the user category

None – No category specified

Notes – Extra information in the form

Office – Office location in the business category

Pager – Phone number in the pager category

Search – Keywords in the search category

Please note the difference between None and Disabled enumerations.

But setting the AutoCompleteType property will only direct browser to not to give options for autocomplete, it doesn’t removers yellow background.

Remove Yellow background

Any code used to set the background color of textbox will fail in following conditions (regardless of run time or design time):

a) Specifying BackColor

b) Specifying background-color in CSS or Style attribute.

The one and only perfect way to do is :

a) Specify a CSS class for the textbox, e.g.

.txtNameStyle

{

font-size:12px;

height:13px;

border-style:none;

background-color: #666666 !important;

color:#ffffff;

}

b) Now declare the text box control so that it looks like this :

<asp:TextBox ID=”txtName” runat=”server” CssClass=”txtNameStyle” Width=”219px”></asp:TextBox>

Note:

The if the background is !important in Css-Style, the input is not considered by Google Toolbar. That’s all what we need.

Now the last step is to just test the page into Internet Explorer.

That’s all for this post, hope you will like it.
Please leave a comment for any help.

For more articles updates and sourcecodes please visit dotnetcoderoom


Update database data using SQL Cursors based on conditions

Recently one of my MSSQL database got SQL Injection attacks.
Hacker put some JavaScript code in all row data to get hits on his website (which is apparently blocked, and soon my site will also be got banned if it keep happening for a long time).

Because the database has a huge amount of data, i can’t update table data using ExecuteNonQuery commands as it will result in a great overload on database and network resources.

So I decided to make something logical which is fast and logical way to handle this situation, and at last i ended up with writing a cursor.

This cursor finds a specific string and replaces it with null.

Scenario:

Create a table with sample data

create table tblDataUpdateTest
(
slno int identity(1,1),
cName varchar(50),
cRemarks varchar(50),
)

insert into tblDataUpdateTest (cName, cRemarks) values (‘name1′,’some text here BADCODE’)
insert into tblDataUpdateTest (cName, cRemarks) values (‘name2′,’raBADCODEhul’)
insert into tblDataUpdateTest (cName, cRemarks) values (‘name3′,’dj BADCODEis devil’)

select * from tblDataUpdateTest


Create Cursor to update database table

Declare @@counter int
set @@counter=0
Declare @@slno int
Declare @@cRemarks varchar(100)

Declare tmepTbl cursor
For
Select slno,cRemarks from tblDataUpdateTest

Open tmepTbl /* Opening the cursor */

fetch next from tmepTbl
into @@slno,@@cRemarks

while @@fetch_Status-1
begin

Update tblDataUpdateTest
set cRemarks = Replace(@@cRemarks,’BADCODE’,”)
where slno = @@slno

fetch next from tmepTbl
into @@slno, @@cRemarks

set @@counter=@@counter+1
end
close tmepTbl
Deallocate tmepTbl

Conclusion:

By running this cursor all the occurrences of BADCODE will be eliminated from the specified table.

Note:
I used word BADCODE here but in my actual data it was a java script tag which was creating all the problem.

For more articles updates and sourcecodes please visit dotnetcoderoom


Change fore color of control using Java Script

Many times we need to set the fore color or back color of controls (e.g. label, button etc).

This can be achieved using CSS (supposing all of you know that) also but we can also do it using Java Script.

This is a simple java script trick so you can use it with html controls as well as asp.net server controls.

Here is an example for doing this :

Code:

<a href=”contact.aspx” class=”mainMenuNormalStyle” onmouseover=”style.color=’#FFB537′;”
onmouseout=”style.color=’#6D6E71′”>CONTACT</a>

<a href=”contact.aspx” class=”mainMenuNormalStyle” onmouseover=”style.backgroundcolor=’#FFB537′;”
onmouseout=”style.backgroundcolor=’#6D6E71′”>CONTACT</a>

In the above code example i set the value of style collection’s color property on the “onmouseover” event and reversed on “onmouseout” event
For more articles updates and sourcecodes please visit dotnetcoderoom


XML Serialization in .Net Framework (Write Xml from Dataset)

WHAT IS SERIALIZATION ?
Serialization is converting an object to a format in which it can be saved (exported) as file or a physical medium. A simple and basic example would be, if we create an XML from a Dataset it is called Serialization.

CODE:
try
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = ConfigurationManager.ConnectionStrings[“DatabaseConnectionString1”].ToString();

SqlConnection myConnection = new SqlConnection(connStr);
String sql = “select * from tblCategory”;
da = new SqlDataAdapter(sql, myConnection);
ds.Clear();
da.Fill(ds, “tblCategory”);
ds.WriteXml(Server.MapPath(“~/xmls/info.xml”));
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

The above code will write an XML file called info.xml from a Dataset called “ds” into xmls folder in root of website.

Options
Alternatively we can use some advanced options to format the data which is being written.

ds.WriteXml(Server.MapPath(“~/xmls/info.xml”, XmlWriteMode.WriteSchema);

Some options are. Some of the attributes available in Microsoft .Net Framework are as follows:

XmlWriteMode.DiffGram — Writes the entire DataSet as a DiffGram.
XmlWriteMode.IgnoreSchema — Writes the current contents of the DataSet as XML data, without an XML Schema Definition language (XSD) schema.
XmlWriteMode.WriteSchema — Writes the current contents of the DataSet as XML data with the relational structure as inline XSD schema.
For more articles updates and sourcecodes please visit dotnetcoderoom


Add meta tags dynamically to a page having a master page in Asp.Net

As a master page provides a common layout to all pages, and <head> tag is included in the master page itself instead of content page.  So one questing comes how to add different meta tags to all different pages (or dynamically generate meat tags) .

This post describes adding a meta tag in an dynamic page with dynamically generated content. This code can be used if you want to add meta tag to a page which is using Master pages.

Two approaches can be taken for this, one is using .net framework’s features, and second is by playing with “ContentPlaceHold”.

Approach 1 : Using .net framework’s features to add meta tags

Add the code below in page_load event of the content page.

Dim metaDescription As New HtmlMeta()
metaDescription.Name = “metaTagHeading (example: keywords, description)”
metaDescription.Content = “A description or content of meta tag here”
Me.Header.Controls.Add(metaDescription)


Approach 2 : Playing with “ContentPlaceHold”.

Step1

Put one content place holder in your master page in HEAD section, like::

<head id=”Head1″ runat=”server”>
<asp:ContentPlaceHolder runat=”server” id=”ContentHeaders”></asp:ContentPlaceHolder>
</head>

Step2

Now in the content (child) page, put this code:

<asp:Content ID=”Content2″ ContentPlaceHolderID=”ContentHeaders” runat=”server”>
<TITLE><%=pageTitle%></TITLE>
<META name=”keywords” content=”<%=varKeywords%>”>
<META name=”description” content=”<%=varDescription%>”>
</asp:Content>

Step3
In content page’s vb or cs file code:

Declare variables as below in the global declaration section (not in page load)

Protected pageTitle As String = “”
Protected varKeywords As String = “”
Protected varDescription As String = “”

Step4
Fill values in page_load event:

pageTitle = “Your Meta Tag ”
varKeywords = “Your Meta Tag ”
varDescription = “Your Meta Tag ”

**End of article**

For more articles updates and sourcecodes please visit dotnetcoderoom