ali raza

C#, .Net ,Asp.net and my thoughts

How to use Check boxes in DataList

 This is html code for  datalist

 <asp:DataList ID=”dlist” runat=”server” RepeatColumns=”3″ OnItemDataBound=”dlist_ItemDataBound”                                      Width=”681px” ItemStyle-HorizontalAlign=”Left”>

<ItemTemplate>       

  <asp:CheckBox ID=”chkBlogSites” runat=”server” />

</ItemTemplate>

</asp:DataList>

   

IN Code Behind OnItemDatabound Event look like

 protected void dlist_ItemDataBound(object sender, DataListItemEventArgs e){

if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)

{

// Here we get the reference of check box

   CheckBox lit = (CheckBox)e.Item.FindControl(“chkBlogSites”);

   if (lit != null)

{

//bind it with database field, in my case i bind name feild of table

      lit.Text = DataBinder.Eval(e.Item.DataItem, “Name”).ToString() ;      lit.Checked = true;

         }

      }

    }

     Here the user define method where i get the value of selected textboxes 

 private void GetCheckedBlogs(){//DataListItem _obj = null;//naviagate in datalist item to fine which item is checked foreach (DataListItem _obj in dlist.Items)

     {

//check other than first row where names are mentioned

if (_obj.ItemIndex > -1)

{ 

   CheckBox _checkBox = (CheckBox)_obj.FindControl(“chkBlogSites”);

   if (_checkBox.Checked == true) 

     {

        Response.write(_checkBox.Text);

      }

   }

}

}

5 responses to “How to use Check boxes in DataList

  1. thuy June 20, 2007 at 8:12 pm

    I like your codes, it’s very simple and clean. In this code all checkboxes in the datalist are checked based on the datasource, do you know how to only check the one that are selected? say you have 10 items on the datalist but only 3 were checked and saved in the table, how can you pull those 3 items and checked them for update or display purpose? Is there a way? Thanks.

  2. sarz September 3, 2007 at 3:53 pm

    Nice code, i love this

  3. sathya December 28, 2007 at 6:40 am

    Hai friends,

    i have use 2005 platform in Asp.net

    I have using 10 items on the datalist but only 3 were checked then automatically or button click corresponding form should be open: Is there a way? i tried this but no errors, no reaction;i attached my code pl verify and find out errors:

    datalistiembound event:
    If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
    If Not lit Is Nothing Then
    e.Item.FindControl(“checkbox1″)
    End If
    End If

    Private Sub getcheckblog()
    ‘DataListItem(obj = Nothing)
    Dim obj As DataListItem
    For Each obj In DataList1.Items
    ‘foreach (DataListItem obj in dlist.Items)

    If (obj.ItemIndex > -1) Then
    Dim _checkBox As CheckBox = CType(obj.FindControl(“checkbox1″), CheckBox)
    If _checkBox.Checked = True Then
    Response.Write(_checkBox.Text)
    Response.Redirect(“DisplayHospital.aspx”)

    End If
    End If
    Next

    Advance Thanks For
    All Reply
    suji

  4. manhtuyen May 2, 2008 at 10:04 am


    [$Profile]
     | 
    [$Photos]
     | 
    [$Scrapbook]
     | 
    [$Blogs]
     |
    [$Groups]



    About this entry

    <a href=”>

    <asp:HyperLink ID=”lnkPicture2″ runat=”server” NavigateUrl=”>

    <img width=”80px” height=”80px” src=”
    style=”border: 0;” />
    <asp:Label ID=”lblID” Text=” Visible=”false” runat=”server”>

    <asp:Label ID=”lblInfomationcomment” runat=”server” Text=”>

    <asp:Label ID=”lblTimeComment” runat=”server” Text=”>

    <asp:Label ID=”lblUserComment” runat=”server” Text=”>

    <asp:LinkButton ID=”btDelete” CommandName=”Delete” Text=”Delete” CommandArgument=”
    runat=”server”>

    // code
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using VietRoom;
    using VietRoom.DataAccessLib;
    using System.Drawing;
    using AjaxControlToolkit;
    using FredCK.FCKeditorV2;
    using FredCK.FCKeditorV2.FileBrowser;

    public partial class displayBlogDetails : VietRoom.Language.BaseLanguagePage
    {
    const int RATING1_MIN = 1;
    const int RATING1_MAX = 5;
    protected static string blogid = “”;
    private string ProfilePictureID = “”;
    protected static string Friend = “”;
    private string photoId = “”;
    protected static Boolean test = false;
    protected void Page_Load(object sender, EventArgs e)
    {

    if (Request.QueryString["blogid"] != null)
    {
    blogid = Request.QueryString["blogid"];
    }
    if (Request.QueryString["Userid"] == null)
    {
    ReturnUrl = HttpContext.Current.Request.Url.ToString();
    }
    if (!IsPostBack)
    {
    labelCaption1.Visible = false;
    labelValue1.Visible = false;
    Friend = Request.QueryString["Userid"];
    Loadcontent();
    PopulateLink();
    //Evaluate_Rating1(Rating1.CurrentRating);
    if (!TestUserInput())
    {
    btEdit.Visible = false;
    }
    }
    }
    private string ReturnUrl
    {
    get
    {
    return Session["ReturnUrl"] as string;
    }
    set
    {
    Session["ReturnUrl"] = value;
    }
    }
    protected Boolean TestUserInput()
    {
    Friend = Request.QueryString["Userid"];
    blogid = Request.QueryString["blogid"];
    DataTable dt = new DataTable();
    dt = WebBlogEntriesAccess.getUseridByBlogId(blogid);
    if (dt.Rows.Count > 0)
    {
    string userid = dt.Rows[0]["UserId"].ToString();
    if (Friend == userid)
    {
    test = true;
    }
    else
    {
    test = false;
    }
    }
    return test;
    }
    private void PopulateLink()
    {
    blogid = Request.QueryString["blogid"];
    DataTable dt = new DataTable();
    dt = WebBlogEntriesAccess.getUseridByBlogId(blogid);
    if (dt.Rows.Count > 0)
    {
    string UserId = dt.Rows[0]["UserId"].ToString();
    HyperLink19.NavigateUrl = “displayBlog.aspx?UserId=” + UserId;
    HyperLink16.NavigateUrl = “displaySameProfile.aspx?userid=” + UserId;
    HyperLink18.NavigateUrl = “displayScrapbook.aspx?userid=” + UserId;
    HyperLink20.NavigateUrl = “displayGroup.aspx?userid=” + UserId;
    }

    }
    protected string getlink()
    {
    blogid = Request.QueryString["blogid"];
    DataTable dt = new DataTable();
    dt = WebBlogEntriesAccess.getUseridByBlogId(blogid);
    if (dt.Rows.Count > 0)
    {
    string userid = dt.Rows[0]["UserId"].ToString();
    return “~/displaySameProfile.aspx?Userid=” + userid;
    }
    return “”;
    }

    protected void Loadcontent()
    {
    DateTime dt1 = DateTime.Now;
    blogid = Request.QueryString["blogid"];
    /* dua rated vao trang neu israte=true */
    string rate = “”;
    int numberrated = WebBlogCommentAccess.getavgRatedByBlogID(blogid);
    if (numberrated > 0)
    {
    if (WebBlogEntriesAccess.TestIsReted(blogid))
    {
    for (int i = 0; i < 5; i++)
    {
    if (i < numberrated)
    {
    rate = rate + ” “;
    }
    else
    {
    rate = rate + ” “;
    }
    }
    }
    else
    {
    rate = “”;
    table1.Visible = false;
    }
    }
    else
    {
    rate = “”;
    }
    lblrated.Text = rate;
    DataTable dt = new DataTable();
    dt = WebBlogEntriesAccess.getUseridByBlogId(blogid);
    if (dt.Rows.Count > 0)
    {
    string userid = dt.Rows[0]["UserId"].ToString();
    ProfilePictureID = UserProfilePictureAccess.GetDefaultProfileID(userid);

    if (ProfilePictureID != “”)
    {
    lcPhotoDisplay.Visible = true;
    lcPhotoDisplay.ImageUrl = “PhotoDisplay.ashx?size=medium&photoid=” + ProfilePictureID;
    }
    else
    {
    lcPhotoDisplay.Visible = false;
    }
    lbluser.Text = dt.Rows[0]["UserId"].ToString();
    DateTime dateadded = (DateTime)dt.Rows[0]["DateAdded"];

    lbloriginal.Text = dateadded.ToString(“MM/dd/yyy,hh:mm:ss”);
    lblcomment.Text = “”;
    lblsubject.Text = dt.Rows[0]["csSubject"].ToString();
    lblmessage.Text = dt.Rows[0]["csMessage"].ToString();
    DateTime datepost = (DateTime)dt.Rows[0]["DateAdded"];
    lblPosteddate.Text = “Posted: ” + datepost.ToString(“f”);
    lblngay.Text = datepost.ToString(“D”);
    int Countcomment = WebBlogCommentAccess.CountBlogByBlogid(blogid);
    lblcountcomment.Text = “NumberComment: (” + Countcomment.ToString() + “)”;
    lblcomment.Text = “Comment: (” + Countcomment.ToString() + “)”;
    int countuser = WebBlogCommentAccess.CountUserByBligId(blogid);
    lblvotesresult.Text = “(” + countuser.ToString() + “)”;
    PupupuxGridBlog();
    }
    }
    protected void uxGridBlog_ItemCommand(object source, DataListCommandEventArgs e)
    {
    if (e.CommandName.Equals(“Delete”))
    {
    string Commentid = Convert.ToString(e.CommandArgument);
    WebBlogCommentAccess.DeleteWebBlogCommentByID(Commentid);
    PupupuxGridBlog();
    Page.Response.Redirect(“~/displayBlogDetails.aspx?blogid=” + blogid + “&Userid=” + Friend, true);
    }
    }

    protected void PupupuxGridBlog()
    {
    DataTable dt1 = new DataTable();
    dt1 = WebBlogCommentAccess.getAllBlogCommentByBlogid(blogid);
    CollectionPager1.PageSize = 10;
    CollectionPager1.DataSource = dt1.DefaultView;
    CollectionPager1.BindToControl = uxGridBlog;
    uxGridBlog.DataSource = CollectionPager1.DataSourcePaged;

    }
    protected void uxGridBlog_ItemDataBound(object sender, DataListItemEventArgs e)
    {
    if (e.Item.ItemType == ListItemType.SelectedItem)
    {
    photoId = Convert.ToString(DataBinder.Eval(e.Item.DataItem, “ProfilePictureID”));

    }
    LinkButton btDelete = (LinkButton)e.Item.FindControl(“btDelete”);
    if (btDelete != null)
    {
    btDelete.Attributes.Add(
    “onclick”,
    “if (confirm(‘[$Are you sure you want to delete this entry]?’)) {} else {return false}”);
    }
    if (!TestUserInput())
    {
    btDelete.Visible = false;
    }
    }
    public void Evaluate_Rating1(int value)
    {

    if (Request.QueryString["Userid"] == null)
    {
    Response.Redirect(“UserLogin.aspx”);
    }
    else
    {
    labelValue1.Text = EvaluateRating(value, Rating1.MaxRating, RATING1_MIN, RATING1_MAX);
    if (!WebblograteAccess.TestUserBy(blogid, Friend))
    {
    WebblograteAccess.Create(blogid, Friend, DateTime.Now, value.ToString());
    Loadcontent();
    Page.Response.Redirect(“~/displayBlogDetails.aspx?blogid=” + blogid + “&Userid=” + Friend, true);
    }
    else
    {
    WebblograteAccess.Update(value.ToString(), blogid, Friend);
    Loadcontent();
    Page.Response.Redirect(“~/displayBlogDetails.aspx?blogid=” + blogid + “&Userid=” + Friend, true);
    }
    }
    }
    protected void Rating1_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
    {
    Evaluate_Rating1(int.Parse(e.Value));
    }
    public static string EvaluateRating(int value, int maximalValue, int minimumRange, int maximumRange)
    {
    int stepDelta = (minimumRange == 0) ? 1 : 0;
    double delta = (double)(maximumRange – minimumRange) / (maximalValue – 1);
    double result = delta * value – delta * stepDelta;
    return FormatResult(result);
    }

    public static string FormatResult(double value)
    {
    return String.Format(“{0:g}”, value);
    }
    protected Boolean CreateComment()
    {
    if (Request.QueryString["Userid"] == null)
    {
    Response.Redirect(“UserLogin.aspx”);
    return false;
    }
    if (FCKeditor1.Value == “”)
    {
    return false;
    }
    WebBlogCommentAccess.Create(blogid, DateTime.Now, Friend, FCKeditor1.Value);
    PupupuxGridBlog();
    Loadcontent();
    return true;
    }
    protected void btSubmit_Click(object sender, EventArgs e)
    {
    if (CreateComment())
    {
    Friend = Request.QueryString["Userid"];
    blogid = Request.QueryString["blogid"];
    Response.Redirect(“displayBlogDetails.aspx?blogid=” + blogid + “&Userid=” + Friend);

    }
    }
    protected void btEdit_Click(object sender, EventArgs e)
    {
    Friend = Request.QueryString["Userid"];
    Response.Redirect(“displayEditBlogEntry.aspx?Blogid=” + blogid + “&fromID=” + Friend);
    }

    }

  5. Reena August 26, 2008 at 11:46 am

    Nice ….
    Tnx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: