All posts tagged gridview

How to Loop through GridView Rows? GridViewRow

We need to loop through or navigate the GridView rows from outsite the GridView control’s event.

For example, you need to navigate all the rows in a gridview control and find a child control placed inside it. The sample code below helps you to find a Checkbox placed inside a GridView control.

C# code

 
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox CheckBox1 = (CheckBox)gvrow.FindControl("CheckBox1");
if (CheckBox1.Checked)
{
// we write this code for find a label value
   Label lblLookFor = (Label)gvrow.FindControl("lblLookFor");
string lookfor = lblLookFor.Text;
//Do your operations here.
}
}

Filling a Grid with Files in a Folder – C#

This code sample shows, in C#, how to get all the files within a specific folder, and list them all, including the file size, in a Gridview control.

To access the FileSystem, you’ll need to import the System.IO namespace, and to use a DataTable, you must import the System.Data namespace:
using System.IO;
using System.Data;


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_01_Filling_a_Grid_with_Files_in_a_Folder._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
  <div style="text-align:center">
	        <asp:Label ID="lblHeader" runat="server"></asp:Label>
	        <asp:GridView ID="grdFiles" runat="server">
	            </asp:GridView>
	    </div>

    </form>
</body>
</html>

C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

namespace _01_Filling_a_Grid_with_Files_in_a_Folder
{
    public partial class _Default : System.Web.UI.Page
    {
        String FilePath;

        protected void Page_Load(object sender, EventArgs e)
        {
            FilePath = Server.MapPath("~/Files");
            GetFiles();  //call the GetFiles method
            lblHeader.Text = "Files in " + FilePath;

        }
        private void GetFiles()
        {
            //Create the DataTable, with columns in which to add the file list
            DataTable dt = new DataTable();
            dt.Columns.Add("FileName", typeof(System.String));
            dt.Columns.Add("Size", typeof(System.String));
            DataRow dr = null;
            DirectoryInfo dir = new DirectoryInfo(FilePath);

            // Iterate through the datatable,
            // adding file to a new row, along with the  filesize to each row
            foreach (FileInfo fi in dir.GetFiles())
            {
                dr = dt.NewRow();
                dr[0] = fi.Name.ToString();
                dr[1] = fi.Length.ToString("N0");  //'N0'formats the number with commas
                dt.Rows.Add(dr);
            }
            // Bind DataTable to GridView - voila!
            grdFiles.DataSource = dt;
            grdFiles.DataBind();
        }

    }
}

How to get OUT parameter from MySQL stored procedure in asp.net

In this tutorial we use the previous tutorial form. And modify the c# code to insert data in mysql using store procedure and we will try to get the next insert id from the the mysql database using out put parameter. Last we i an facing a problem to get the out put parameter value from the mysql database but there is not good tutorial on this with asp.net. So it inspire me to write an article to get the value of the output parameter value from mysql. How to create storeprocedure in mysql please read my previous article .
Insert in to MySQL with ASP.NET – Part 2

Here we just give the save button code and show this output parameter value in out message box. You can download the full code by link given at the end of this article.

     protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // Connection string for a typical local MySQL installation
                string cnnString = "Server=localhost;Port=3306;Database=ci_series;Uid=root;Pwd=";

                // Create a connection object 
                MySqlConnection connection = new MySqlConnection(cnnString);

                // call store procedure
                MySqlCommand cmd = new MySqlCommand("insert_membership", connection);

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("?first_name", MySqlDbType.VarChar).Value = txtFirstName.Text;
                cmd.Parameters.Add("?last_name", MySqlDbType.VarChar).Value = txtLastName.Text;
                cmd.Parameters.Add("?username", MySqlDbType.VarChar).Value = txtUserName.Text;
                cmd.Parameters.Add("?password", MySqlDbType.VarChar).Value = txtPassword.Text;
                cmd.Parameters.Add("?email_address", MySqlDbType.VarChar).Value = txtEmail.Text;


                cmd.Parameters.Add(new MySqlParameter("?rows", MySqlDbType.Int32));
                cmd.Parameters["?rows"].Direction = ParameterDirection.Output;


                connection.Open();

                cmd.ExecuteNonQuery();

                int rows = (int)cmd.Parameters["?rows"].Value;

                lblError.Text = "Data Saved. " + "New Id will be " + rows.ToString();
            }

            catch (MySqlException ex)
            {
                lblError.Text = "Insert failed with: " + ex.Message;
            }



        }

[smProductImageAdd src="http://learneveryday.net/codecanyon/adverticement/add_codecnayon_smart-social-share-asp.net.png" alt= "Smart Social Share" href="http://codecanyon.net/item/smart-social-share/160097" title="Smart Social Share (Asp.net control)" description="Smart Social share is a asp.net control . Which helps you to give user to share your content with social book mark site." ref="marifdu"]

Create a store procedure using MySQL Administrator. The code is bellow. In my sql we use out as a return parameter value which we can get from the font end by code. And we give this parameter direction as ParameterDirection.Output;

DELIMITER $$

DROP PROCEDURE IF EXISTS `insert_membership` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_membership`(

IN first_name varchar(25),
IN last_name varchar(25),
IN username varchar(25),
IN password varchar(10),
IN email_address varchar(50),
out rows int


)
BEGIN

INSERT INTO membership (
first_name,
last_name,
username,
password,
email_address
)

VALUES(
first_name,
last_name,
username,
password,
email_address

) ;

select LAST_INSERT_ID() into rows;

END $$

DELIMITER ;

After insert data using store procedure you can see the successful message like bellow.
insert mysql and return output.

To learn more about store procedure you can read Stored Procedure Parameters and
MySQL Stored Procedure – INSERT – Example

Bellow is the link to download the sample code used in this tutorial.

Conditional Gridview Text – Checkboxes

This code sample shows how to either show or make invisible, a checkbox in each row of the Gridview, along with making text conditional, based on certain criteria. In this case, if the Postal code starts with a non-numeric character, we change it to “Alt Text”, and we set the Visible property of the checkbox in that row to “False”. Here we use a numerical check function to check where there the substring is numeric or not.
The final out put is here :
Gridview Conditional Checkbox
Html code :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_03_Gridview_Conditional_Checkbox._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<asp:GridView OnRowDataBound="doDataCheck" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" ID="GridView2" runat="Server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ck1" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First" />
<asp:BoundField DataField="LastName" HeaderText="Last" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
<asp:BoundField DataField="country" HeaderText="country" />
</Columns>
<HeaderStyle BackColor="Blue" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="Select FirstName, LastName, Title, Address, City, Region, PostalCode, country from Employees">
</asp:SqlDataSource>
    </form>
</body>
</html>

The default.aspx code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace _03_Gridview_Conditional_Checkbox
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void doDataCheck(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
               
              
                CheckBox chkExp = (CheckBox)e.Row.FindControl("ck1");
                string sCode = e.Row.Cells[5].Text;
               if( !IsNumeric(sCode.Substring(1,1))){
                   e.Row.Cells[4].Text = "<i style='color:red'>(Alt Text)</i>";
                   chkExp.Visible= false;
               }
            }
        }
        // IsNumeric Function
        static bool IsNumeric(object Expression)
        {
            // Variable to collect the Return value of the TryParse method.
            bool isNum;

            // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
            double retNum;

            // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
            // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
            isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
            return isNum;
        }	
    }
}

You can download the code from bellow.

Gridview – Conditional Images

This Gridview sample shows how to, for each row, based on other data within that row, to show a different image. We do this by creating a TemplateField, and putting an ASP.Net Image control within it, called ‘Image1′.

Then, inside the RowDataBound event of the Gridview, we put code, which first, checks and finds the Image control in that row, and then assigning a different JPG file to the ImageURL property of that image. One other thing here, you’ll notice, is that when the criteria is matched, we set the Image control’s Visible property to ‘True’. The defalut Image control’s Visible property to ‘False’.

Naturally, since we’re checking one particular column in the Gridview for this data, we’re using a Select Case statement.
For this we create class to load the data in gridview. You can load data in gridview from database and use this technic to show conditional image.
grid view conditional image
Here is the html markup


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_02_Gridview_Conditional_Images._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
  onrowdatabound="GridView1_RowDataBound">
<Columns>

<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HtmlEncode="False"
HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="Discount" HeaderText="Discount" SortExpression="Discount"  HtmlEncode="False" Visible="true" />

<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="Image1" runat="server"  />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
    </form>
</body>
</html>


[smProductImageAdd src="http://learneveryday.net/codecanyon/adverticement/add_codecnayon_smart-social-share-asp.net.png" alt= "Smart Social Share" href="http://codecanyon.net/item/smart-social-share/160097" title="Smart Social Share (Asp.net control)" description="Smart Social share is a asp.net control . Which helps you to give user to share your content with social book mark site." ref="marifdu"]

The class to load Product .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


public class Product
{
   
 public Product()
    {
    }

 public Product(int productid, string productname,
                            int unitinstock, int unitprice,int discount
                                        )
                 { this.ProductID = productid;
                 this.ProductName = productname;
                 this.UnitsInStock = unitinstock;
                 this.UnitPrice = unitprice;
                 this.Discount = discount;
                 }
private int _productid;
public int ProductID
    {
        get { return _productid; }
        set { _productid = value; }
    }

    private string _productname;
    public string ProductName
    {
        get { return _productname; }
        set { _productname = value; }
    }
    private int _unitinstock;
    public int UnitsInStock
    {
        get { return _unitinstock; }
        set { _unitinstock = value; }
    }
    private int _unitprice;
    public int UnitPrice
    {
        get { return _unitprice; }
        set { _unitprice = value; }
    }
    private int _discount;
        public int Discount
    {
        get { return _discount; }
        set { _discount = value; }
    }
    
    public static List<Product> GetList()
    {
        List<Product> product = new List<Product>();

        product.Add(new Product(1, "Chai", 39, 18,15));
        product.Add(new Product(2, "Chef Anton's Cajun Seasoning", 3, 12,25));
        product.Add(new Product(3,	"Grandma's Boysenberry Spread"	,120	,25,30));
	    product.Add(new Product(4,	"Uncle Bob's Organic Dried Pears",	15	,30,50));

        return product;
    }
 }

Finally the code behind the defalult.aspx page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace _02_Gridview_Conditional_Images
{
    public partial class _Default : System.Web.UI.Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            DataBind();
        }
        public void DataBind()
        {
            GridView1.DataSource = Product.GetList();
            GridView1.DataBind();
        }
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Image img = (Image)e.Row.FindControl("image1");
                switch (int.Parse(e.Row.Cells[4].Text))
                {
                    case 15:
                        img.ImageUrl = "/images/discount_15.jpg";
                        img.Visible = true;
                        break;
                    case 25:
                        img.ImageUrl = "/images/discount_25.jpg";
                        img.Visible = true;
                        break;
                    case 30: 
                        img.ImageUrl = "/images/discount_30.jpg";
                        img.Visible = true;
                        break;
                    case 50: 
                        img.ImageUrl = "/images/discount_50.jpg";
                        img.Visible = true;
                        break;
                    default: 
                        img.Visible = false;
                        break;
                }
            }


        }
    }
}

You can download the code from bellow link.