Want the databinding to work on an empty dataset.

mathieu_cupryk
mathieu_cupryk used Ask the Experts™
on
I have the following and in code snippet what I am trying to do is remove the sqldatasource

protected void BindDropDownList()
        {
            DataList1.DataSource = GetBinaryImagesByUserId.GetBinaryImages(strUsrId);
            DataList1.DataBind();
            // Select * into Dataset it will fail if empty.
            GridView1.DataSource = GetBinaryImagesByUserId.GetBinaryImages(strUsrId);
            GridView1.DataBind();

        }
How can we duplicate so it works like the below.
  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:LocalSqlServer %>"
            SelectCommand="SELECT * FROM [aspnet_Images]"></asp:SqlDataSource>
        <br />
        <asp:DataList Visible="false" ID="DataList1" runat="server" DataKeyField="ImagesId" DataSourceID="SqlDataSource1" CellSpacing="15" EnableViewState="false"
            RepeatColumns="4" OnItemDataBound="DataList1_ItemDataBound">
            <ItemTemplate>
                <cc1:RbmBinaryImage ID="RbmBinaryImage2" runat="server" DisplayThumbnail="True"  EmptyImageUrl="images/NoPhoto.JPG" /><br />
                <asp:Literal runat="server" ID="literal1" Text='<%# Eval("ImagesTitle") %>'></asp:Literal><br />
            </ItemTemplate>
        </asp:DataList></div>
       
        <div>
            <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="ImagseId" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="ImagesId" HeaderText="ImagesId" InsertVisible="False" ReadOnly="True"
                        SortExpression="ImagesId" />
                    <asp:BoundField DataField="ImagesTitle" HeaderText="ImagesTitle" SortExpression="ImagesTitle" />
                    <asp:TemplateField HeaderText="BinaryImage">
                        <ItemTemplate>
                            <cc1:RbmBinaryImage ID="RbmBinaryImage2" runat="server"  ImageContent='<%# Eval("ImagesContent") %>'  EmptyImageUrl="images/NoPhoto.JPG" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
This works I want t oremove the datasource.


<asp:DataList Visible="false" ID="DataList1" runat="server"
        DataKeyField="ImagesId"
        CellSpacing="15" EnableViewState="false" RepeatColumns="4"
        OnItemDataBound="DataList1_ItemDataBound">
        <ItemTemplate>
            <cc1:RbmBinaryImage ID="RbmBinaryImage2" runat="server" DisplayThumbnail="True" EmptyImageUrl="~/images/NoPhoto.JPG" /><br />
            <asp:Literal runat="server" ID="literal1" Text='<%# Eval("ImagesTitle") %>'></asp:Literal><br />
        </ItemTemplate>
    </asp:DataList>
</div>
 
<div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="ImagesId" HeaderText="ImagesId" InsertVisible="False" ReadOnly="True"
                SortExpression="ImagesId" />
            <asp:BoundField DataField="ImagesTitle" HeaderText="ImagesTitle" SortExpression="ImagesTitle" />
            <asp:TemplateField HeaderText="BinaryImage">
                <ItemTemplate>
                    <cc1:RbmBinaryImage id="RbmBinaryImage2" runat="server" imagecontent='<%# Eval("ImagesContent") %>'
                        emptyimageurl="~/Images/NoPhoto.JPG" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
This does not work when the dataset is empty.
-------------------------------------------------------------------------------
 
 
 
 
 
 
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestDBConnectionString %>"
            SelectCommand="SELECT * FROM [ImageTest]"></asp:SqlDataSource>
        <br />
        <asp:DataList Visible="false" ID="DataList1" runat="server" DataKeyField="ImageId" DataSourceID="SqlDataSource1" CellSpacing="15" EnableViewState="false"
            RepeatColumns="4" OnItemDataBound="DataList1_ItemDataBound">
            <ItemTemplate>
                <Rbm:RbmBinaryImage ID="RbmBinaryImage2" runat="server" DisplayThumbnail="True"  EmptyImageUrl="~/images/NoPhoto.JPG" /><br />
                <asp:Literal runat="server" ID="literal1" Text='<%# Eval("ImageTitle") %>'></asp:Literal><br />
            </ItemTemplate>
        </asp:DataList></div>
        
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ImageId" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="ImageId" HeaderText="ImageId" InsertVisible="False" ReadOnly="True"
                        SortExpression="ImageId" />
                    <asp:BoundField DataField="ImageTitle" HeaderText="ImageTitle" SortExpression="ImageTitle" />
                    <asp:TemplateField HeaderText="BinaryImage">
                        <ItemTemplate>
                            <Rbm:RbmBinaryImage ID="RbmBinaryImage2" runat="server"  ImageContent='<%# Eval("ImageContent") %>'  EmptyImageUrl="~/images/NoPhoto.JPG" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
when dataset is empty, the gridview doesn't binding, Instead of this add a Template Called 'EmptyDataTemplate' its shows 'No record found'


<asp:GridView ID="GridView1" runat="server">
        <Columns>
        
        </Columns>
        <EmptyDataTemplate>
        No records found.
        </EmptyDataTemplate>
        
        </asp:GridView>

Open in new window

Author

Commented:
i am confused.
Commented:
dhansmani is saying to put the code:

<EmptyDataTempalte>
No records found
</EmptyDataTemplate>

into the code of your gridview after the </Columns> statement so your first gridview will be like this:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="ImagesId" HeaderText="ImagesId" InsertVisible="False" ReadOnly="True"
                SortExpression="ImagesId" />
            <asp:BoundField DataField="ImagesTitle" HeaderText="ImagesTitle" SortExpression="ImagesTitle" />
            <asp:TemplateField HeaderText="BinaryImage">
                <ItemTemplate>
                    <cc1:RbmBinaryImage id="RbmBinaryImage2" runat="server" imagecontent='<%# Eval("ImagesContent") %>'
                        emptyimageurl="~/Images/NoPhoto.JPG" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
<EmptyDataTempalte>
No records found
</EmptyDataTemplate>
    </asp:GridView>

HTH
-M3mph15

Expert Spotlight: Joe Anderson (DatabaseMX)

We’ve posted a new Expert Spotlight!  Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.

Author

Commented:
Can you tell me if I did this right.

The first thing is when we have the dataset then we can do anything with it.

We don't have to bind it right away.

This is a copy of a routine a built.

 protected DataSet LoadGridDataSet()
        {
            String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["dbaspnetConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            cmd.Connection = con;
           
            try
            {
                conn.Open(); //open the connection
                SqlCommand myCommand = new SqlCommand("select * from tbl_image where UserId=@UserId", conn);
                cmd.CommandType = CommandType.Text;


                // Add Parameters to Command
                SqlParameter UserId = new SqlParameter("@UserId", SqlDbType.UniqueIdentifier);
                UserId.Value = strUsrId;
                myCommand.Parameters.Add(UserId);

                SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
                DataSet myDataSet = new DataSet();
                myAdapter.Fill(myDataSet);

                foreach (DataRow dRow in myDataSet.Tables[0].Rows)
                {
                    Response.ContentType = dRow["img_type"].ToString();
                    byte[] imageContent = (byte[])((dRow["img_stream"]));
                    Response.BinaryWrite(imageContent);
                }
               
                conn.Close();
                return ds ;
            }
            catch (SqlException SQLexc)
            {
                Response.Write("Data Retrival Failure. Error Details : " + SQLexc.ToString());
                con.Close();
                sda.Dispose();
                con.Dispose();
            }
        }

Author

Commented:
Now I can change this to be.

 public void displayImages()
    {
            GridView1.DataSource = LoadGridDataSet;
            GridView1.DataBind();


        }
 

Author

Commented:
 protected void btnUploadImage_Click(object sender, EventArgs e)
        {
            RbmBinaryImage1.ImageContent = FileUpload1.FileBytes;
            string connection = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connection);
            System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("InsertInto_tbl_Images");
            command.CommandType = CommandType.StoredProcedure;
            command.Connection = con;
            command.Parameters.Add(new System.Data.SqlClient.SqlParameter("img_title", FileUpload1.FileName));
            command.Parameters.Add(new System.Data.SqlClient.SqlParameter("img_stream", FileUpload1.FileBytes));
            command.Parameters.Add(new System.Data.SqlClient.SqlParameter("img_type", ""));
            command.Parameters.Add(new System.Data.SqlClient.SqlParameter("UserID", strUsrId));

            con.Open();
            command.ExecuteNonQuery();

        }
The FileUpload1
is empty,
Commented:
You could test if the dataset is empty.

Try using myDataSet.Tables[0].Rows.Count.

If the COunt is larger then 0 then databind if not then don't.

Though the EmptyDataTemplate is a good way of letting the user know that no records were found.

Author

Commented:
I forgot to do the binding

<div>
        <asp:DataList Visible="false" ID="DataList1" runat="server" DataKeyField="img_id"
            CellSpacing="15" EnableViewState="false" RepeatColumns="4" OnItemDataBound="DataList1_ItemDataBound">
            <ItemTemplate>
                <cc1:rbmbinaryimage id="RbmBinaryImage2" runat="server" displaythumbnail="True" emptyimageurl="~/images/NoPhoto.JPG" />
                <br />
                <asp:Literal runat="server" ID="literal1" Text='<%# Eval("img_title") %>'></asp:Literal><br />
            </ItemTemplate>
        </asp:DataList>
    </div>
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="img_id" HeaderText="img_id" InsertVisible="False" ReadOnly="True"
                    SortExpression="img_id" />
                <asp:BoundField DataField="img_title" HeaderText="img_title" SortExpression="img_title" />
                <asp:TemplateField HeaderText="BinaryImage">
                    <ItemTemplate>
                        <cc1:rbmbinaryimage id="RbmBinaryImage2" runat="server" imagecontent='<%# Eval("img_stream") %>'
                            emptyimageurl="~/Images/NoPhoto.JPG" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EmptyDataTemplate>
                No records found
            </EmptyDataTemplate>
        </asp:GridView>

This is my ui and the behind is
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using OmegaLove.BLL;
using System.Drawing;
using Telerik.Web.UI;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using OmegaLove.RbmControls;



namespace OmegaLove.Web.UI
{
    public partial class ctrlUserProfilePics : OmegaLoveBasePageUserControl
    {

        private string strUsrId;

        private void Page_Load(object sender, EventArgs e)
        {
            System.Web.Security.MembershipUser mu = System.Web.Security.Membership.GetUser();
            strUsrId = mu.ProviderUserKey.ToString();

            if (!Page.IsPostBack)
            {
               
            }



        }

        protected void btnUploadImage_Click(object sender, EventArgs e)
        {
            RbmBinaryImage1.ImageContent = FileUpload1.FileBytes;
            string connection = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connection);
            System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("InsertInto_tbl_Images");
            command.CommandType = CommandType.StoredProcedure;
            command.Connection = con;
            command.Parameters.Add(new System.Data.SqlClient.SqlParameter("img_title", RbmBinaryImage1.ImageUrl));
            command.Parameters.Add(new System.Data.SqlClient.SqlParameter("img_stream", FileUpload1.FileBytes));
            command.Parameters.Add(new System.Data.SqlClient.SqlParameter("img_type", RbmBinaryImage1.MimeType));
            command.Parameters.Add(new System.Data.SqlClient.SqlParameter("UserID", strUsrId));

            con.Open();
            command.ExecuteNonQuery();

        }

        protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
        {

            //ImageContent='<%# Eval("ImageContent") %>'
            RbmBinaryImage DynamicImage = (RbmBinaryImage)e.Item.FindControl("RbmBinaryImage2");
            if (DynamicImage != null)
                DynamicImage.ImageContent = (byte[])((DataRowView)e.Item.DataItem).Row["img_stream"];

        }

        //private DataSet LoadGridDataSet()
        //{
        //    String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["dbaspnetConnectionString"].ConnectionString;
        //    SqlConnection conn = new SqlConnection(strConnString);
           
        //    try
        //    {
        //        conn.Open(); //open the connection
        //        SqlCommand myCommand = new SqlCommand("select * from tbl_image where UserId=@UserId", conn);
        //        myCommand.CommandType = CommandType.Text;


        //        // Add Parameters to Command
        //        SqlParameter UserId = new SqlParameter("@UserId", SqlDbType.Text);
        //        UserId.Value = strUsrId;
        //        myCommand.Parameters.Add(UserId);

        //        SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
        //        DataSet myDataSet = new DataSet();
        //        myAdapter.Fill(myDataSet);

        //        foreach (DataRow dRow in myDataSet.Tables[0].Rows)
        //        {
        //            Response.ContentType = dRow["img_type"].ToString();
        //            byte[] imageContent = (byte[])((dRow["img_stream"]));
        //            Response.BinaryWrite(imageContent);
        //        }
        //        conn.Close();
        //        myAdapter.Dispose();
        //        conn.Dispose();
        //        return myDataSet;
        //    }
        //    catch (SqlException SQLexc)
        //    {
        //        Response.Write("Data Retrival Failure. Error Details : " + SQLexc.ToString());
        //        return null;
        //    }
        //}

        //public void displayImages()
        //{
        //    GridView1.DataSource = LoadGridDataSet();
        //    GridView1.DataBind();
        //}

        private DataTable GetData(SqlCommand cmd)
        {
            DataTable dt = new DataTable();
            String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["dbaspnetConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                return dt;
            }
            catch
            {
                return null;
            }
            finally
            {
                con.Close();
                sda.Dispose();
                con.Dispose();
            }
        }
    }
}


What should I do?

Author

Commented:
k

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial