Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for the ‘C# 2.0’ Category

How to hide Gridview column programmatically?

Posted by Ramani Sandeep on April 7, 2009

Question :  How to hide Gridview column programmatically?

Solution :

The Columns collection only stores the explicitly declared columns, so if you’re using autogenerated columns, the count will be zero.
If you’re using autogenerated column, after databind you could loop through the rows collection and make the appropriate cells invisible, like:

        GridView1.DataBind();
        if (GridView1.Columns.Count > 0)
            GridView1.Columns[0].Visible = false;
        else
        {
            GridView1.HeaderRow.Cells[0].Visible = false;
            foreach (GridViewRow gvr in GridView1.Rows)
            {
                gvr.Cells[0].Visible = false;
            }
        }

Hope this will help you !!!

Happy Programming

Posted in ASP.NET, C# 2.0 | Tagged: , , , | 58 Comments »

Programming the web.config File Using C#

Posted by Ramani Sandeep on April 7, 2009

What Is web.config?

The web.config file is the application’s configuration file. It is typically used to configure an ASP.NET Web application and define the configuration settings for the Web application. It typically contains the application-wide settings, such as database connection string, culture settings, authentication, and authorization information, etc. In ASP.NET 1.x, much effort was required to manipulate the web.config file programmatically. With ASP.NET 2.0 however, this can be done quite easily and efficiently. The following section discusses how this can be achieved.

The Configuration API in ASP.NET 2.0

The configuration API of ASP.NET 2.0 adds a great level of flexibility in that it allows us to add or edit a configuration file seamlessly in ASP.NET. The WebConfigurationManager class in the System.Web.Configuration namespace has the OpenWebConfiguration method that can be used to open the configuration file of the application as a Configuration object for reading from or writing to the configuration file. The virtual path to the configuration file is specified to this method as a parameter.

The following code snippet displays all the keys of the appSettings section of the web.config file:

Listing – 1

        Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");

        AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
        if (appSettingsSection != null)
        {
            foreach (string key in appSettingsSection.Settings.AllKeys)
            {
                Response.Write(key);
            }
        }


The following method can be used to modify a specific key — value pair of the web.config file — programmatically using C#:

Listing – 2

        public void Modify(string key, string value)
        {
            Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
            if (appSettingsSection != null)
            {
                appSettingsSection.Settings[key].Value = value;
                config.Save();
            }
        }

The following method can be used to delete a specific key in the web.config file programmatically using C#:

Listing – 3

        public void Remove(string key)
        {
            Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
            if (appSettingsSection != null)
            {
                appSettingsSection.Settings.Remove(key);
                config.Save();
            }
        }

Conclusion

Even if modifying a web.config file programmatically can be a handy solution in some situations, it is not recommended to do so frequently in a Web application, as any change in the web.config file will restart the Web server and refresh the cache entries.

Posted in ASP.NET, C# 2.0 | Tagged: , , , , | 16 Comments »

Capcha Image Code in C#

Posted by Ramani Sandeep on January 29, 2009

Introduction

CAPTCHA stands for “completely automated public Turing test to tell computers and humans apart.” What it means is, a program that can tell humans from machines using some type of generated test. A test most people can easily pass but a computer program cannot.

You’ve probably encountered such tests when signing up for an online email or forum account. The form might include an image of distorted text, like that seen above, which you are required to type into a text field.

The idea is to prevent spammers from using web bots to automatically post form data in order to create email accounts (for sending spam) or to submit feedback comments or guestbook entries containing spam messages. The text in the image is usually distorted to prevent the use of OCR (optical character reader) software to defeat the process. Hotmail, PayPal, Yahoo and a number of blog sites have employed this technique.

This article demonstrates how to create such an image and employ it within an ASP.NET web form.

Using the code

The code file contains the source for one class and two web forms. To use it, just create a new web project and add those items.

* CaptchaImage.cs – defines the CapchaImage object which actually creates the image.
* Default.aspx, Default.aspx.cs – a sample web form.
* JpegImage.aspx, JpegImage.aspx.cs - a web form designed to output a JPEG image rather than HTML.

Let’s look at each component and it’s purpose.

CaptchaImage.cs

The CaptchaImage object creates an image given parameters for the text to be displayed, the image dimensions and, optionally, the font to use.The heart of the code is the GenerateImage() method, shown below, which creates a bitmap image of the specified width and height. This method is called from the CaptchaImage constructor, so the image is ready as soon as you create a new instance of the object.To create the image, we first fill in the background using a hatched brush (the “dirtier” the image appears, the harder it is for an OCR program to read it).

To make the text fit within the image, we start with an initial font size based on the image height and use the Graphics.MeasureString() method to find the resulting dimensions of the drawn text. If the text exceeds the image dimensions, we reduce the font size and test again and again until a suitable font size is found.

// ===========================================

// Creates the bitmap image.

// ===========================================

private void GenerateImage()
{
// Create a new 32-bit bitmap image.

Bitmap bitmap = new Bitmap(
this.width,
this.height,
PixelFormat.Format32bppArgb);

// Create a graphics object for drawing.

Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);

// Fill in the background.

HatchBrush hatchBrush = new HatchBrush(
HatchStyle.SmallConfetti,
Color.LightGray,
Color.White);
g.FillRectangle(hatchBrush, rect);

// Set up the text font.

SizeF size;
float fontSize = rect.Height + 1;
Font font;
// Adjust the font size until the text fits within the image.

do
{
fontSize–;
font = new Font(
this.familyName,
fontSize,
FontStyle.Bold);
size = g.MeasureString(this.text, font);
} while (size.Width > rect.Width);

// Set up the text format.

StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;

// Create a path using the text and warp it randomly.

GraphicsPath path = new GraphicsPath();
path.AddString(
this.text,
font.FontFamily,
(int) font.Style,
font.Size, rect,
format);
float v = 4F;
PointF[] points =
{
new PointF(
this.random.Next(rect.Width) / v,
this.random.Next(rect.Height) / v),
new PointF(
rect.Width – this.random.Next(rect.Width) / v,
this.random.Next(rect.Height) / v),
new PointF(
this.random.Next(rect.Width) / v,
rect.Height – this.random.Next(rect.Height) / v),
new PointF(
rect.Width – this.random.Next(rect.Width) / v,
rect.Height – this.random.Next(rect.Height) / v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

// Draw the text.

hatchBrush = new HatchBrush(
HatchStyle.LargeConfetti,
Color.LightGray,
Color.DarkGray);
g.FillPath(hatchBrush, path);

// Add some random noise.

int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
{
int x = this.random.Next(rect.Width);
int y = this.random.Next(rect.Height);
int w = this.random.Next(m / 50);
int h = this.random.Next(m / 50);
g.FillEllipse(hatchBrush, x, y, w, h);
}

// Clean up.

font.Dispose();
hatchBrush.Dispose();
g.Dispose();

// Set the image.

this.image = bitmap;
}

Once the font is set, we define a GraphicsPath() which essentially converts the text to a set of lines and curves. This can then be distorted using the GraphicsPath.Warp() method with some randomly generated values. The effect is similar to holding a cardboard sign up by opposite corners and giving it a bit of a twist. The resulting path is drawn onto the image, again using a hatch brush to give it a “dirty” appearance.

To complete the distortion, small blots are randomly painted over the image. You could experiment with other effect to thwart OCRs, but keep in mind that it should still be legible to humans, some of whom may have visual impairments

Default.aspx

This is a very simple sample web form that contains only a few basic elements, namely an <IMG> tag for the image, a text box and a “Submit” button.

<form id=”Default” method=”post” runat=”server”>
<img src=”JpegImage.aspx”><br>
<p>
<strong>Enter the code shown above:</strong><br>
<asp:TextBox id=”CodeNumberTextBox” runat=”server”></asp:TextBox>
<asp:Button id=”SubmitButton” runat=”server” Text=”Submit”>
</asp:Button><br>
</p>
<p>
<em class=”notice”>
(Note: If you cannot read the numbers in the above<br>
image, reload the page to generate a new one.)</em>
</p>
<p><asp:Label id=”MessageLabel” runat=”server”></asp:Label></p>
</form>

Note that the SRC attribute of the <IMG> tag points to the web form JpegImage.aspx.

The code-behind for Default.aspx simply generates a random text string for the image and validates that this text was entered by the user when the form is submitted.

The key is to store the text string in the Session object.

private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)

// Create a random code and store it in the Session object.

this.Session["CaptchaImageText"] = GenerateRandomCode();

else
{
// On a postback, check the user input.

if (this.CodeNumberTextBox.Text ==
this.Session["CaptchaImageText"].ToString())
{
// Display an informational message.

this.MessageLabel.CssClass = “info”;
this.MessageLabel.Text = “Correct!”;
}
else
{
// Display an error message.

this.MessageLabel.CssClass = “error”;
this.MessageLabel.Text = “ERROR: Incorrect, try again.”;

// Clear the input and create a new random code.

this.CodeNumberTextBox.Text = “”;
this.Session["CaptchaImageText"] = GenerateRandomCode();
}
}
}

The reason for storing the text string in the Session object is so that it can be accessed by JpegImage.aspx.

JpegImage.aspx

For this web form, no HTML is needed (what’s there is just the default code generated by Visual Studio when the file was created). Instead of HTML, the code will produce a JPEG image.In the code-behind, we first create a CaptchaImage object, using the text retrieved from the Session object. This creates a bitmap image for us.

private void Page_Load(object sender, System.EventArgs e)
{
// Create a CAPTCHA image using the text stored in the Session object.

CaptchaImage ci = new CaptchaImage(
this.Session["CaptchaImageText"].ToString(),
200, 50, “Century Schoolbook”);

// Change the response headers to output a JPEG image.

this.Response.Clear();
this.Response.ContentType = “image/jpeg”;

// Write the image to the response stream in JPEG format.

ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);

// Dispose of the CAPTCHA image object.

ci.Dispose();
}

We then modify the HTTP response headers to set the Content-type to “image/jpeg” so the client browser will know we are sending an image.The last step is to retrieve the bitmap image from CaptchaImage.Image and write it to the HTTP response output stream in JPEG format. Fortunately, the Save() method of the Bitmap object makes this simple. Any other supported image format could be used as well so long as the Content-type header is set accordingly.

Posted in ASP.NET, C# 2.0 | Tagged: , , , | 10 Comments »

Scrolling News Web Control using ASP.Net and C#

Posted by Ramani Sandeep on January 6, 2009

On many of the web portals/sites it is observed that latest news start scrolling from right to left.

To do this need to write JavaScript in detail, there could be number of storing news format. I have written this web control to avoid extensive use of JavaScript by using Marquee at server side.

I have tested this application on following browsers:

1. Internet Explorer 6.0
2. Netscape Navigator 7.2
3. Mozilla Firefox 1.5

So no need to worry much about cross browser performance issue, it work simply great on all above browsers.

Requirement:

Need To make following tables in SQL Server Database, and put corresponding records in the tables.

News Table

create table News
(
newsId  int  primary key identity(1,1) Not null,
newTitle varchar(50) Not null,
dateCreated datetime
)

The code behind of page i.e. on page load I have following code

News.ascx.cs

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Fill News Section
            FillNews();
        }
    }

    private void FillNews()
    {
        // Fetch News Records from Database and Store in Datatable…

        string news = null;

        for (int i = 0; i < DataTable.Rows.Count; i++)
        {
            news = news + DataTable.Rows[i]["News"].ToString();
            news = news + "  ||  ";
        }

        lblNews.Text = news;
    }

Which just prepare a connection with the database and get the newsTitle and dateCreated to scroll in the marquee in direction=’UP’. I have prepared a string which can be added dynamically in a table row to fit in appropriate table row, which generates scrolling news section with anchor (link) to open detail in the new window. Idea behind opening in new window to stick the user to same site. You can do following with the marquee and JavaScript functionality used in the same.

  • Can stop on mouseover of the link [OnMouseOver='this.stop();']
  • Can start on mouseout of the link [OnMouseOut='this.start();']
  • Can controll the speed of the scrolling [direction='up' scrollamount='2']

Register this control as below in a file in which you want to use this

<%@  Control Language="C#" AutoEventWireup="true" CodeFile="News.ascx.cs" Inherits="UserControls_News" %>
<table width="100%" cellspacing="0px" cellpadding="0px" class="NewsBgColor">
    <tr>
        <td class="Table_TD_Center">
            <marquee behavior="SCROLL" width="100%" scrolldelay="100″" onmouseover='this.stop();'
                onmouseout='this.start();'>
                <asp:Label ID="lblNews" runat="server" Text="" CssClass="RedLabel">
                </asp:Label>
            </marquee>
        </td>
    </tr>
</table>

That’s all … Happy Programming

Posted in ASP.NET, C# 2.0 | Tagged: , | 11 Comments »

Displaying Alert Message Boxes from your .aspx page

Posted by Ramani Sandeep on December 17, 2008

Step 1 : Create a General class and place the following Code in it

public static void CreateMessageAlert(System.Web.UI.Page senderPage,
string alertMsg, string alertKey)
{
ScriptManager.RegisterStartupScript(senderPage, senderPage.GetType(), alertKey, “alert(‘” + alertMsg + “‘);”,true);
}

Step 2 : Call the created method from where ever you wish to send the alert from


string alertmessage = “Thank You for visiting DotNetSpider.com”;

YourClassName.CreateMessageAlert(this,alertmessage,”alertKey”);

Where YourClassName is nothing but the name of the class file where your
CreateMessageAlert method resides and alertmessage is where you assign the
string you wish to display.

Posted in ASP.NET, C# 2.0, JavaScript | Tagged: , , | 1 Comment »

Strip Non Numeric Values from a string

Posted by Ramani Sandeep on December 8, 2008

/// <summary>

/// this function strips non-numeric values out of a string and returns the numeric content of a string.

/// </summary>

/// <param name=”Value”></param>

/// <returns></returns>

public static string StripNonNumeric(string Value)

{

return System.Text.RegularExpressions.Regex.Replace(Value, “\\D”, “”);

}

Posted in ASP.NET, C# 2.0 | Tagged: , , | Leave a Comment »

Fill Year in DDL

Posted by Ramani Sandeep on November 16, 2008

here is the code to fill year dropdownlist :

int intYear = System.DateTime.Now.Year;

for (int i = 78; i >= 0; i–)
{
string strYear = Convert.ToString(intYear – i);

ddlYear.Items.Add(new ListItem(strYear, strYear));
}
ddlYear.Items.Insert(0, new ListItem(“Year”, “-1″));

this is simple ..but very usefull code..

Posted in ASP.NET, C# 2.0 | Tagged: , | Leave a Comment »

Gridview – Insert , Update , Delete

Posted by Ramani Sandeep on November 16, 2008

Pre-requisites

Your project or website must be ASP.NET AJAX enabled website. Because we are going to add the GridView in an UpdatePanel. So your GridView control will be look smart without unnecessary postbacks. You need to create a Customer Table with 6 columns for Customer Code[Code], Name[Name], Gender[Gender], City[City], State[State] and Customer Type[Type], with your desired data types. Then create a class file in your App_Code folder and create a Default.aspx along with code-behind file Default.aspx.cs.

Step 1. Create Class File ‘CustomersCls.cs’

We need to create a class file to do database manipulations such as select, insert, delete and update data in the Customer Table. So we add a class file as ‘CustomersCls.cs’ in App_Code section.

Let us write five methods in the class file as follows

    public void Insert(string CustomerName, string Gender, string City, string State, string CustomerType)
    {
        // Write your own Insert statement blocks
    }
    public DataTable Fetch()
    {
        // Write your own Fetch statement blocks, this method should return a DataTable
    }
    public DataTable FetchCustomerType()
    {
        // Write your own Fetch statement blocks to fetch Customer Type from its master table and this method
        //should return a DataTable
    }
    public void Update(int CustomerCode, string CustomerName, string Gender, string City, string State, string CustomerType)
    {
        // Write your own Update statement blocks.
    }
    public void Delete(int CustomerCode)
    {
        // Write your own Delete statement blocks.
    }

Step 2: Make Design File ‘Default.aspx’

In the Default.aspx page, add an UpdatePanel control. Inside the UpdatePanel, add a GridView, set AutoGenerateColumns as False. Change the ShowFooter Flag to True and set the DataKeyNames your column name for Customer Code and Customer Type, in our case it is Code and Type. Then click on the Smart Navigation Tag of the GridView control, choose Add New Column and add 5 BoundField columns with DataField values as Name, Gender, City, State and Type, plus 2 CommandField columns with one for Edit/Update and another for Delete functions. Now your GridView control is ready. But as first step, we need to add some new records into the database. For that we need to place the controls in the Footer row. So we have to convert all these BoundField columns as TemplateField columns. To do this again, click on the Smart Navigation Tag on the GridView choose Edit Columns, the Field’s property window will open. Select column by column from Name to Customer Type, include also Edit column, and select ‘Convert this field into a TemplateField’. Now all the BoundField columns will be

converted to TemplateField columns except the Delete column.

Column[0] – Name

Right click on the GridView control, select Edit Template, choose column[0] – Name, you can view a label placed in the ItemTemplate section and a TextBox placed in the EditItemTemplate section. Add another Texbox in the FooterTemplate section and name it as txtNewName.

Column[1] – Gender

Now again select Edit Template, choose column[1] – Gender, replace the TextBox with a DropDownList,name it as cmbGender, add Male and Female as their ListItem values. On the Edit DataBindings of the cmbGender, add Eval(“Gender”) to its selectedvalue. Add another DropDownList in the FooterTemplate section and name it as cmbNewGender.

Column[2] –City & Column[3] – State

Add Texboxes in both column’s FooterTemplate section and name it as txtNewCity and txtNewState respectively.

Column[4] – Type

In this column’s EditItemTemplate section, replace the TextBox with a DropDownList, name it as cmbType. Also add another DropDownList in the FooterTemplate section and name it as cmbNewType. Both these DropDownList’s we are going to fill with dynamic data from database. So specify both DropDownList’s DataTextField and DataValueField as Type.

Column[5] – Edit

Just add a link button into the FooterTemplate section, specify its CommandName property as ‘AddNew’.

For your persual, we have provided the complete source code of the GridView control below. The State column in our sample is read-only. So you cannot find TextBox for that column in the EditItemTemplate section.

Source Code of the GridView Control

     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Code, Type"
            OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound"
            OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand"
            ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
            <Columns>
                <asp:TemplateField HeaderText="Name" SortExpression="Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtNewName" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Gender">
                    <EditItemTemplate>
                        <asp:DropDownList ID="cmbGender" runat="server" SelectedValue='<%# Eval("Gender") %>'>
                            <asp:ListItem Value="Male" Text="Male"></asp:ListItem>
                            <asp:ListItem Value="Female" Text="Female"></asp:ListItem>
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Eval("Gender") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="cmbNewGender" runat="server">
                            <asp:ListItem Selected="True" Text="Male" Value="Male"></asp:ListItem>
                            <asp:ListItem Text="Female" Value="Female"></asp:ListItem>
                        </asp:DropDownList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtNewCity" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("City") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="State" SortExpression="State">
                    <EditItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("State") %>'></asp:Label>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtNewState" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("State") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Type">
                    <EditItemTemplate>
                        <asp:DropDownList ID="cmbType" runat="server" DataTextField="Type" DataValueField="Type">
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label5" runat="server" Text='<%# Eval("Type") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="cmbNewType" runat="server" DataTextField="Type" DataValueField="Type">
                        </asp:DropDownList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit" ShowHeader="False">
                    <EditItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                            Text="Update"></asp:LinkButton>
                        <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                            Text="Cancel"></asp:LinkButton>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew"
                            Text="Add New"></asp:LinkButton>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
                            Text="Edit"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
            </Columns>
        </asp:GridView>

Step 3: Make Code-behind File ‘Default.aspx.cs’

Now we are going to do the code-behind part of this page. Les us explain you event by event coding on each methods. In the code-behind page, create an instance for the Customer class as follows:

CustomersCls customer=new CustomersCls();

Then create a private method ‘FillCustomerInGrid’ to retrieve the existing customer list from the database and bind it to the GridView. The CustomersCls class’s Fetch() method is used and it returns the data to a DataTable. On first stage it will return empty rows. So you cannot see any header,data or even footer rows of the GridView control. You can only see an empty space or you see only the EmptyDataText. So you cannot add any new data from the footer row.

private void FillCustomerInGrid()
    {
        DataTable dtCustomer = customer.Fetch();
        if (dtCustomer.Rows.Count > 0)
        {
            GridView1.DataSource = dtCustomer;
            GridView1.DataBind();
        }
        else
        {
            dtCustomer.Rows.Add(dtCustomer.NewRow());
            GridView1.DataSource = dtCustomer;
            GridView1.DataBind();

            int TotalColumns = GridView1.Rows[0].Cells.Count;
            GridView1.Rows[0].Cells.Clear();
            GridView1.Rows[0].Cells.Add(new TableCell());
            GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GridView1.Rows[0].Cells[0].Text = "No Record Found";
        }
    }

In this article, we have provided a workaround to fix this problem. Closely look at the method FillCustomerInGrid, there is a conditional statement to check the rows exists in DataTable or not.Now go to the else part of the if statement, see the block of code we provided there. Simply we have added an empty row to the DataTable. Then bind it to the GridView control. To give a professional look to the GridView control, we do little bit more by providing ColumnSpan and set a Text as “No Record Found”, this text will be displayed if the GridView is empty without any rows and you can see

both the Header and Footer of the GridView control.

Initialize GridView control

In the page load event, we have to call this FillCustomerInGrid method as follows,

protected void Page_Load(object sender, EventArgs e)
{
      If (!IsPostBack)
     {
           FillCustomerInGrid();
     }
}

Fill DropDownList in GridView with dynamic values

In column[4] – Type, there are two DropDownList controls, one in the EditItemTemplate section (cmbType) and another in FooterTemplate (cmbNewType). We have to fill both these DropDownList controls with some dynamic data. If you look at our CustomersCls class, we have a separate method called FetchCustomerType. In the RowDataBound event of the GridView control insert the following code.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");

            if (cmbType != null)
            {
                cmbType.DataSource = customer.FetchCustomerType();
                cmbType.DataBind();
                cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
            }
        }

        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");
            cmbNewType.DataSource = customer.FetchCustomerType();
            cmbNewType.DataBind();
        }
    }

Previously in this article, we have set the DataKeyNames values as Code, Type. If you see in the above code, we use one of the DataKeyNames value as the SelectedValue for the cmbType control, this is to retain the value of the cmbType in EditMode. The index value of Code is 0 and Type is 1. So we use as follows

cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

So far we have initialized the GridView control with the datatable and also make some values to be filled in the Footer DropDownList cmbNewType. Run the application, you can see the GridView only with the Footer row and data in the cmbNewType control. Let us start to code for adding new records into the database when we click ‘Add New’ linkbutton.

Add New Records from GridView control

Create an event for the GridView’s RowCommand and add the following code in it.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtNewName = (TextBox)GridView1.FooterRow.FindControl("txtNewName");
            DropDownList cmbNewGender = (DropDownList)GridView1.FooterRow.FindControl("cmbNewGender");
            TextBox txtNewCity = (TextBox)GridView1.FooterRow.FindControl("txtNewCity");
            TextBox txtNewState = (TextBox)GridView1.FooterRow.FindControl("txtNewState");
            DropDownList cmbNewType = (DropDownList)GridView1.FooterRow.FindControl("cmbNewType");

            customer.Insert(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text,

            cmbNewType.SelectedValue);
            FillCustomerInGrid();

        }
    }

In the above code, we are declaring and finding the controls in the GridView’s footer section and use the CustomersCls class insert method to add the new data into the database. Then we are calling the FillCustomerInGrid method to fill the GridView control with the newly inserted values. Now save everything and run your application. Put some test data in the Textboxes and select some values in the DropDownLists and click on the Add New linkbutton. You can see data inserted into the database

and listed in the GridView control.

Edit and Update in GridView

In the RowEditing event of the GridView, add the following lines of code. This will switch a specific row of the GridView to Edit Mode.

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) 
{
   GridView1.EditIndex = e.NewEditIndex; 
   FillCustomerInGrid();
}

After the GridView swithes to Edit Mode, you can view the TextBoxes and DropDownlList controls along with Update and Cancel linkbuttons in the Edit mode. To cancel this action, add the following two lines of code in the GridView’s RowCancelingEdit event.

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) 
{ 
   GridView1.EditIndex = -1;
   FillCustomerInGrid(); 
} 

You can update the data to the customer table, by adding the following lines of code in the GridView’s RowUpdating event.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
{
    TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName"); 
    DropDownList cmbGender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbGender"); 
    TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity"); 
    DropDownList cmbType = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbType");   
    customer.Update(GridView1.DataKeys[e.RowIndex].Values[0].ToString(),txtName.Text,cmbGender.SelectedValue,txtCity.Text,CustomerType.SelectedValue); 

    GridView1.EditIndex = -1; 
    FillCustomerInGrid(); 

}

The above block of codes in RowUpdating event, finds the control in the GridView, takes those values in pass it to the CustomersCls class Update method.

The first parameter GridView1.DataKeys[e.RowIndex].Values[0].ToString() will return the Code of the Customer. That is the unique code for each customer to perform update function.

Delete in GridView

To delete a row from the customer table, add the following lines of code in the GridView’s RowDeleting event. Here you have to pass the unique Code of customer which is in GridView1.DataKeys[e.RowIndex].Values[0].ToString() to the Delete method of the CustomersCls class.

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 
    customer.Delete(GridView1.DataKeys[e.RowIndex].Values[0].ToString()); 
    FillCustomerInGrid(); 
}

Hope this will Help You !!!

Jay Ganesh

Posted in ASP.NET, ASP.NET Ajax, C# 2.0 | Tagged: , , | 22 Comments »

Asp.Net GridView Manipulation Inside DataList Control

Posted by Ramani Sandeep on November 7, 2008

Introduction

To make things clear, we are going to display Customer Information in a GridView control under each Customer State using a DataList and a GridView control. The data listed in the GridView control canbe manipulated with Edit, Update and Delete operations. Along with this, we are going to place a check box control in the first column of the GridView control, by which we can do a ‘Select All’ action for each Customer list separated by in every Customer State. Finally, a prompt confirmation has been added with the Delete LinkButton in the GridView control.

So the entire Html code of the DataList and GridView control will look like below.

Listing – 1

       <asp:DataList ID="DataList1" runat="server" DataKeyField="Cus_State" OnItemDataBound="DataList1_ItemDataBound"
                Width="100%">
                <ItemTemplate>
                    Customer State :
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Cus_State") %>'></asp:Label>
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Cus_State,Cus_Code"
                        GridLines="Horizontal" Width="100%" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing"
                        OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"
                        OnRowUpdating="GridView1_RowUpdating">
                        <Columns>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    <asp:CheckBox ID="chkSelectAll" runat="server" Text="Select all" />
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkCusNo" runat="server" />
                                    <asp:HiddenField ID="hidCusState" runat="server" Value='<%# Bind("Cus_State") %>' />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="Cus_Name" HeaderText="Name"></asp:BoundField>
                            <asp:BoundField DataField="Cus_Gender" HeaderText="Gender"></asp:BoundField>
                            <asp:BoundField DataField="Cus_Age" HeaderText="Age"></asp:BoundField>
                            <asp:BoundField DataField="Cus_City" HeaderText="City"></asp:BoundField>
                            <asp:CommandField HeaderText="Edit" ShowEditButton="True"></asp:CommandField>
                            <asp:CommandField HeaderText="Delete" ShowDeleteButton="True"></asp:CommandField>
                        </Columns>
                        <EmptyDataTemplate>
                            You have deleted all records.
                        </EmptyDataTemplate>
                    </asp:GridView>
                </ItemTemplate>
            </asp:DataList>

We have simplified the code-behind section up to certain extent. The brief steps involved to bind the GridView inside DataList are given below:

Step 1: Bind the DataList in Form Load Event

Listing - 2

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string sql = "Select Distinct Cus_State from Customers";
            SqlDataAdapter da = new SqlDataAdapter(sql, "YourConnectionString");

            DataTable dt = new DataTable();
            da.Fill(dt);

            DataList1.DataSource = dt;
            DataList1.DataBind();
        }
    }

Step 2: In ItemDataBound Event of DataList control, bind the GridView control.

Since we are going to use binding of GridView control frequently in every event, we write a private method as below.

Listing - 3

    private void BindGrid(GridView GridView, string CusState)
    {
        string sql = "Select Cus_No, Cus_Name, Cus_Gender, Cus_Age, Cus_City, Cus_State from";
        sql = sql + " Customers Where Cus_State='" + CusState+ "'";

        SqlDataAdapter da = new SqlDataAdapter(sql, "YourConnectionString");
        DataTable dt = new DataTable();
        da.Fill(dt);

        GridView.DataSource = dt;
        GridView.DataBind();
    }

BindGrid function takes two parameters such as GridView object and a string CusState, i.e. Customer State to fetch the records corresponding only to the Customer State. Then call this method in the ItemDataBound event of the DataList control as follows.

Listing - 4

    protected void DataList1_ItemDataBound (object sender, DataListItemEventArgs e)
    {
        GridView GridView1 = (GridView)e.Item.FindControl("GridView1");

        BindGrid(GridView1, DataList1.DataKeys[e.Item.ItemIndex].ToString());
    }

First line of code, finds the GridView control inside the DataList control. And the second line, calls the BindGrid function, by passing GridView object and Cus_State field’s value which we have already bound with the DataList in the DataKeyField properly.

Believe it or not, hit F5 button once, your default browser will popped up, with a DataList displaying Customer State, and each row of the DataList will have a GridView control with corresponding Customers belongs to the State displayed in the DataList.

GridView Control Data Manipulations:

Step 1: GridView Row Editing Event

Listing - 5

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView GridView1 = (GridView)sender;
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid(GridView1, GridView1.DataKeys[e.NewEditIndex][0].ToString());
    }

Line 1: Creates GridView object from the sender, to identify which GridView control firing the ‘Edit’ event.
Line 2: Assign the EditIndex from the GridView events NewEditIndex.
Line 3: Call the BindGrid function by passing the created GridView object and the Customer State value taken from the DataKeyNames property.

Step 2: GridView Row Editing Cancel Event

Listing - 6

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView GridView1 = (GridView)sender;
        GridView1.EditIndex = -1;
        BindGrid(GridView1, GridView1.DataKeys[e.RowIndex][0].ToString());
    }

Step 3: GridView Row Updating Event

Listing - 7

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        GridView GridView1 = (GridView)sender;
        TextBox TxCusName = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
        TextBox TxCusGender = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
        TextBox TxtCusAge = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0];
        TextBox TxCusCity = (TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0];

        string sql = "Update Customers Set Cus_Name=@CustomerName,"
        + "Cus_Gender=@CustomerGender, "
        + "Cus_Age=@CustomerAge, Cus_City=@CustomerCity "
        + "Where Cus_Code=@CustomerCode";

        SqlConnection conn = new SqlConnection(ConnectionString);
        conn.Open();

        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@CustomerCode", SqlDbType.Int).Value =    GridView1.DataKeys[e.RowIndex].Values[1].ToString();
        cmd.Parameters.Add("@CustomerName", SqlDbType.VarChar, 50).Value = TxCusName.Text;
        cmd.Parameters.Add("@CustomerGender", SqlDbType.VarChar, 6).Value = TxCusGender.Text;
        cmd.Parameters.Add("@CustomerAge", SqlDbType.Int).Value = TxtCusAge.Text;
        cmd.Parameters.Add("@CustomerCity", SqlDbType.VarChar, 50).Value = TxCusCity.Text;
        cmd.Prepare();
        cmd.ExecuteNonQuery();
        conn.Close();

        GridView1.EditIndex = -1;
        BindGrid(GridView1, GridView1.DataKeys[e.RowIndex][0].ToString());

    }

The above code, finds the textboxes in the GridView Edit mode using the RowIndex property, followed by the usual coding to save the changes into the Database.

Step 4: GridView Row Deleting Event

Listing - 8

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView GridView1 = (GridView)sender;
        string sql = "Delete From Customers Where Cus_Code=@CustomerCode";

        SqlConnection conn = new SqlConnection(ConnectionString);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@CustomerCode", SqlDbType.Int).Value
        = GridView1.DataKeys[e.RowIndex].Values[1].ToString();
        cmd.Prepare();
        cmd.ExecuteNonQuery();
        conn.Close();
        BindGrid(GridView1, GridView1.DataKeys[e.RowIndex][0].ToString());

    }

JavaScript function for ‘Select All’ Checkbox

To add ‘Select All’ checkbox functionality inside the GridView control, we have to work on both the Html and Code sections. In the Html section, we have already added two checkboxes in the GridView’s TemplateField’s HeaderTemplate and ItemTemplate sections. We have also added a HiddenField control along with the checkbox in the ItemTemplate section. To remind again, this HiddenField “hidCusState” will have the value of the Customer State. Now we are going to add a JavaScript function, which will be called when the CheckBox in the HeaderTemplate section is clicked.

Listing - 9

   <script type="text/javascript" language="javascript">
            function fnSelectAll(chkname, cusstate)
            {
                var inputs = document.getElementsByTagName('input');
                var checked=false;
                var hidCusState;

                for(var i=0;i<inputs.length;i++)
                {
                    if (inputs[i].id==chkname && inputs[i].type=="checkbox" && inputs[i].checked==true)
                    {
                        checked=true;
                        break;
                    }
                }

                for(var i=0;i<inputs.length;i++)
                {
                    if (inputs[i].id!=chkname && inputs[i].type=="checkbox")
                    {
                        hidCusState = inputs[i].id.replace("chkCusNo","hidCusState");
                        if (document.getElementById(hidCusState).value==cusstate)
                        inputs[i].checked=checked;
                    }
                }
            }
      </script>

This JavaScript function is exclusively written for web pages that work with MasterPages. Not only that, this function will only ‘checked’ the checkboxes belongs to a single Customer State.

How it works, is this function got two parameters such as the HeaderTemplate's CheckBox name and the value for the Customer State. The Customer State value passed is compared with the HiddenField control’s value, if it matches than that particular checkbox will get checked.

As first step it gets all the elements contains <input /> tags, finds only the ‘Select All’ checkbox, and identify whether it is checked or not. If the ‘Select All’ checkbox is checked then, it loops again to find out all the checkboxes and its corresponding hidden field in the GridView row, match both the cusstate and hidCusState value, and if match found, then change the status to ‘checked’. If the ‘Select All’ checkbox is unchecked, then it works vice-versa.

Now in the code-behind section, in the GridView RowDataBound event, add the following code.

Listing - 10

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //Part 1
        GridView GridView1 = (GridView)sender;
        DataListItem dlItem = (DataListItem)GridView1.Parent;
        DataListItemEventArgs dle = new DataListItemEventArgs(dlItem);
        if (e.Row.RowType == DataControlRowType.Header)
        {
            CheckBox chkSelectAll = (CheckBox)e.Row.FindControl("chkSelectAll");
            chkSelectAll.Attributes.Add("onclick",
            "fnSelectAll('" + chkSelectAll.ClientID + "', '"
            + DataList1.DataKeys[dle.Item.ItemIndex].ToString() + "');");
        }

        //Part 2
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[6].HasControls())
            {
                LinkButton lnkbtnDelete = ((LinkButton)e.Row.Cells[6].Controls[0]);
                lnkbtnDelete.Attributes.Add("onclick", "return confirm('Do you want to Delete?');");
            }
        }
    }

The above code contains two parts. The first part belongs to ‘Select All’ function. In this part, we create an object to the GridView control from the sender object. Then we identify the parent of the GridView control, that is, the DataList item into which the GridView control belongs to. Using the DataListItemEventArgs object, we get the DataKey value of the parent’s DataList’s Item’s Customer State value. Then we find the chkSelectAll control and add the JavaScript function on the onclick event by passing it’s Client Id and the Customer State value of the DataList item.

Confirmation to Delete a Row in GridView control

Part 2 of the above RowDataBound event of the GridView control belongs to the confirmation of Delete functions before deleting a row in the GridView control.

Listing - 11

if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[6].HasControls())
        {
            LinkButton lnkbtnDelete = ((LinkButton)e.Row.Cells[6].Controls[0]);
            lnkbtnDelete.Attributes.Add("onclick", "return confirm('Do you want to Delete?');");
        }
    }

Here we find the Delete LinkButton in the CommandField of the GridView control and then add a JavaScript confirm function on its onclick event.

Hope this article we give you a basic idea of how to manipulate GridView control inside a DataList and how to add JavaScript functions with various functionalities.

Posted in ASP.NET, C# 2.0 | Tagged: , | 4 Comments »

Repeater for MasterDetail

Posted by Ramani Sandeep on November 7, 2008

————————
.ASPX
————————

<div>
<asp:DataList ID=”DataList1″ runat=”server”
onitemdatabound=”DataList1_ItemDataBound”>
<ItemTemplate>
<asp:Label ID=”lblCityName” runat=”server”
Text=’<%# Eval(“CityName”) %>’>
</asp:Label>

<asp:Repeater ID=”rpt” runat=”server”>
<ItemTemplate>
<br />
<asp:Label
ID=”lblprj” runat=”server”
Text=’<%# Eval(“ProjectName”) %>’>
</asp:Label>
</ItemTemplate>
</asp:Repeater>

</ItemTemplate>
</asp:DataList>
</div>

————————
.CS
————————

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

DataTable dt = new DataTable();
DataColumn dc = new DataColumn(“CityName”);
DataColumn dc1 = new DataColumn(“ProjectName”);

dt.Columns.Add(dc);
dt.Columns.Add(dc1);

DataRow dr = dt.NewRow();
dr[0] = “Ahmedabad”;
dr[1] = “Project 1″;
dt.Rows.Add(dr);

DataRow dr0 = dt.NewRow();
dr0[0] = “Ahmedabad”;
dr0[1] = “Project 2″;
dt.Rows.Add(dr0);

DataRow dr1 = dt.NewRow();
dr1[0] = “Baroda”;
dr1[1] = “Project 1″;
dt.Rows.Add(dr1);

mydata = dt;
DataTable dtCity = SelectDistinct(mydata, “CityName”);

DataList1.DataSource = dtCity;
DataList1.DataBind();
}
}

public DataTable mydata
{
get
{
if (ViewState["mydata"] == null)
ViewState["mydata"] = new DataTable();

return (DataTable)ViewState["mydata"];
}
set
{
ViewState["mydata"] = value;
}
}

private bool fieldValuesAreEqual(object[] lastValues, DataRow currentRow, string[] fieldNames)
{
bool areEqual = true;

for (int i = 0; i < fieldNames.Length; i++)
{
if (lastValues[i] == null || !lastValues[i].Equals(currentRow[fieldNames[i]]))
{
areEqual = false;
break;
}
}

return areEqual;
}

private DataRow createRowClone(DataRow sourceRow, DataRow newRow, string[] fieldNames)
{
foreach (string field in fieldNames)
newRow[field] = sourceRow[field];

return newRow;
}

private void setLastValues(object[] lastValues, DataRow sourceRow, string[] fieldNames)
{
for (int i = 0; i < fieldNames.Length; i++)
lastValues[i] = sourceRow[fieldNames[i]];
}

private DataTable SelectDistinct(DataTable SourceTable, params string[] FieldNames)
{
object[] lastValues;
DataTable newTable;
DataRow[] orderedRows;

if (FieldNames == null || FieldNames.Length == 0)
throw new ArgumentNullException(“FieldNames”);

lastValues = new object[FieldNames.Length];
newTable = new DataTable();

foreach (string fieldName in FieldNames)
newTable.Columns.Add(fieldName, SourceTable.Columns[fieldName].DataType);

orderedRows = SourceTable.Select(“”, string.Join(“, “, FieldNames));

foreach (DataRow row in orderedRows)
{
if (!fieldValuesAreEqual(lastValues, row, FieldNames))
{
newTable.Rows.Add(createRowClone(row, newTable.NewRow(), FieldNames));

setLastValues(lastValues, row, FieldNames);
}
}
return newTable;
}

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

DataTable dtProject = mydata.Clone();
DataRow[] dr = mydata.Select(“CityName=’” + ((Label)e.Item.FindControl(“lblCityName”)).Text + “‘”);

for (int i = 0; i < dr.Length; i++)
{
DataRow objdr = dtProject.NewRow();
objdr[0] = dr[i][0];
objdr[1] = dr[i][1];
dtProject.Rows.Add(objdr);
}

((Repeater)e.Item.FindControl(“rpt”)).DataSource = dtProject;
((Repeater)e.Item.FindControl(“rpt”)).DataBind();
}
}

Posted in ASP.NET, C# 2.0 | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 317 other followers