How to make the Datagrid rows clickable

Last post 05-29-2007 4:31 PM by evb5145. 6 replies.

Sort Posts:

  • How to make the Datagrid rows clickable

    05-10-2007, 3:43 PM
    • Loading...
    • evb5145
    • Joined on 06-22-2006, 12:57 PM
    • Washington DC
    • Posts 66

    Hi,

    I followed the suggestions on the web on how to make the Datagrid rows clickable. But when I debug the project, it hangs and I have to stop the debugger. Pls. help and thanks in advance.

    codebehind:

    public class chooseFacility : System.Web.UI.Page

    {

    protected System.Web.UI.WebControls.Label lblChooseFacility;

    protected System.Web.UI.WebControls.TextBox txtChooseFacility;

    protected System.Web.UI.WebControls.Table tblResults;

    protected System.Web.UI.WebControls.Label lblSelect;

    protected System.Web.UI.WebControls.Button btnChooseFacility;

    protected System.Web.UI.WebControls.Label lblEnter;

    protected System.Web.UI.WebControls.TextBox txtSearch;

    protected System.Web.UI.WebControls.Button btnSearch;

    protected System.Web.UI.WebControls.DataGrid dgResults;

     

    private void Page_Load(object sender, System.EventArgs e)

    {

    if (!Page.IsPostBack)

          PopulateTable();

    }

     

    private void PopulateTable()

    {

    int i = 0;

    ((ArrayList)Cache["aUserSites"]).Sort(new CArrayListSort());

    ((ArrayList)((ArrayList)Cache["aRouteSites"])[0]).Sort(new CArrayListSort());

    ((ArrayList)((ArrayList)Cache["aRouteSites"])[1]).Sort(new CArrayListSort());

    DataTable dataTable = new DataTable();

    dataTable.Columns.Add("Name");

    dataTable.Columns.Add("Prov_Num");

    DataRow dataRow;

     

    for (i=0; i<((ArrayList)((ArrayList)Cache["aRouteSites"])[0]).Count; i++)

    {

    if (((ArrayList)Cache["aUserSites"]).BinarySearch(((ArrayList)((ArrayList)Cache["aRouteSites"])[1])[i], new CArrayListSearch()) > -1)

    {

    // Create new row from DataTable.

    dataRow = dataTable.NewRow();

    dataRow["Name"] = ((string)((ArrayList)((ArrayList)Cache["aRouteSites"])[0])[i]);

    dataRow["Prov_Num"] = ((string)((ArrayList)((ArrayList)Cache["aRouteSites"])[1])[i]);

    dataTable.Rows.Add(dataRow);

    }

    }

    DataView dv = new DataView(dataTable);

    Cache["dv"] = dv;

    dgResults.DataSource = dataTable;

    dgResults.DataBind();

    }

    public ArrayList GetSitesFromRoute(string cWildcard)

    {

    string cSqlStmt = "";

    ArrayList aRouteSites = new ArrayList();

    aRouteSites.Add(new ArrayList());

    aRouteSites.Add(new ArrayList());

     

    Sql.SqlConfig oSqlCfg = Sql.loadSqlConfig("webconfigs", "route");

    if (oSqlCfg == null)

    return null;

    string connectionString = "server=" + oSqlCfg.Server + ";" +

    "user id=" + oSqlCfg.User + ";" +

    "password=" + oSqlCfg.Pass + ";" +

    "database=" + oSqlCfg.Database + ";" +

    "pooling=false;" +

    "allowzerodatetime=true";

    MySqlConnection connection = new MySqlConnection(connectionString);

    if (cWildcard.Length < 1)

    cSqlStmt = "select * from webconfigs.route";

    else

    cSqlStmt = "select * from webconfigs.route where NAME like '%" + cWildcard + "%'";

    MySqlCommand command = new MySqlCommand(cSqlStmt, connection);

    connection.Open();

    MySqlDataReader dr = command.ExecuteReader();

    while(dr.Read())

    {

    ((ArrayList)aRouteSites[0]).Add( dr.GetString(dr.GetOrdinal("NAME")).Trim() );

    ((ArrayList)aRouteSites[1]).Add( dr.GetString(dr.GetOrdinal("PROV_NUM")).Trim() );

    }

    dr.Close();

    command.Dispose();

    connection.Close();

    return aRouteSites;

    }

     

     

    public TableCell AddCell(string strItem)

    {

    return AddCell(strItem, 0, "");

    }

    public TableCell AddCell(string strItem, Int16 iWidth)

    {

    return AddCell(strItem, iWidth, "");

    }

    public TableCell AddCell(string strItem, Int16 iWidth, string strClass)

    {

    TableCell cell = new TableCell();

    cell.Text = strItem;

    cell.Attributes["class"] = strClass;

    if (iWidth > 0)

    cell.Width = iWidth;

    return cell;

    }

    public TableRow AddCellToRow(TableCell cell)

    {

    TableRow row = new TableRow();

    row.Cells.Add(cell);

    return row;

    }

    public void CreateaTemp()

    {

    ArrayList aTemp = new ArrayList();

    aTemp.Add(new ArrayList());

    aTemp.Add(new ArrayList());

    }

    #region

    Web Form Designer generated code

    override protected void OnInit(EventArgs e)

    {

    //

    // CODEGEN: This call is required by the ASP.NET Web Form Designer.

    //

    InitializeComponent();

    base.OnInit(e);

    if (Session["oUser"] == null || Session.IsNewSession)

    Session["oUser"] = new User.User();

    ViewState["numberDiv"] = 1;

    Cache["aUserSites"] = ((User.User)(Session["oUser"])).Sites;

    Cache["aRouteSites"] = GetSitesFromRoute("");

    }

     

    /// <summary>

    /// Required method for Designer support - do not modify

    /// the contents of this method with the code editor.

    /// </summary>

    private void InitializeComponent()

    {

    this.btnChooseFacility.Click += new System.EventHandler(this.btnChooseFacility_Click);

    this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);

    this.dgResults.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgResults_ItemCreated);

    this.dgResults.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgResults_SortCommand);

    this.dgResults.SelectedIndexChanged += new System.EventHandler(this.dgResults_SelectedIndexChanged);

    this.Load += new System.EventHandler(this.Page_Load);

    }

    #endregion

    private void dgResults_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)

    {

    // Two way sorting LOGIC

    if( (((int)(ViewState["numberDiv"]))%2) == 0 )

    ((DataView)Cache["dv"]).Sort = e.SortExpression + " " + "ASC";

    else

    ((DataView)Cache["dv"]).Sort = e.SortExpression + " " + "DESC";

     

    ViewState["numberDiv"] = ((int)ViewState["numberDiv"]) + 1;

    dgResults.DataSource = ((DataView)Cache["dv"]);

    dgResults.DataBind();

    }

    private void btnChooseFacility_Click(object sender, System.EventArgs e)

    {

     

    }

    private void btnSearch_Click(object sender, System.EventArgs e)

    {

    Cache["aRouteSites"] = GetSitesFromRoute(txtSearch.Text.Trim());

    PopulateTable();

    }

    private void Old_btnSearch_Click()

    {

    TableCell cell = new TableCell();

    //header row

    TableRow headerRow = new TableRow();

    cell = AddCell("Name", 0, "header");

    headerRow.Cells.Add(cell);

    cell = AddCell("Site", 0, "header");

    headerRow.Cells.Add(cell);

    tblResults.Rows.Add(headerRow);

    tblResults.CellSpacing = 0;

    tblResults.CellPadding = 1;

    Sql.SqlConfig oSqlCfg = Sql.loadSqlConfig("webconfigs", "route");

    if (oSqlCfg == null)

    return;

    string connectionString = "server=" + oSqlCfg.Server + ";" +

    "user id=" + oSqlCfg.User + ";" +

    "password=" + oSqlCfg.Pass + ";" +

    "database=" + oSqlCfg.Database + ";" +

    "pooling=false;" +

    "allowzerodatetime=true";

    MySqlConnection connection = new MySqlConnection(connectionString);

    Cache["cSqlStmt"] = "select * from webconfigs.route where NAME like% " + txtSearch.Text.Trim() + " or where PROV_NUM like% " + txtSearch.Text.Trim();

    MySqlCommand command = new MySqlCommand(((string)Cache["cSqlStmt"]));

    command.Connection = connection;

    connection.Open();

    MySqlDataReader dr = command.ExecuteReader();

    MySqlDataAdapter adapter = new MySqlDataAdapter(command);

    DataSet ds = new DataSet();

    adapter.Fill(ds,"route");

    dgResults.DataBind();

     

    while(dr.Read())

    {

    TableRow Row = new TableRow();

    Row.Attributes["onmouseover"] = "rowOver();";

    Row.Attributes["onmouseout"] = "rowOut();";

    Row.Attributes["style"] = "cursor:hand;";

    Row.Attributes["onclick"] = "selectSite('" + dr.GetString(dr.GetOrdinal("PROV_NUM")).Trim() + "'";

    cell = AddCell(dr.GetString(dr.GetOrdinal("NAME")).Trim() , 0, "lst");

    Row.Cells.Add(cell);

    cell = AddCell(dr.GetString(dr.GetOrdinal("PROV_NUM")).Trim() , 0, "lst");

    Row.Cells.Add(cell);

    tblResults.Rows.Add(Row);

    }

    dr.Close();

    command.Dispose();

    connection.Close();

    }

     

    private void dgResults_SelectedIndexChanged(object sender, System.EventArgs e)

    {

     

    }

    private void dgResults_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)

    {

    /*For Datagrig's with alternating colors

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

    {

    e.Item.Attributes.Add("onmouseover",

    "this.style.backgroundColor='beige';this.style.cursor='hand'");

    e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='#99B3FF';");

    e.Item.Attributes.Add("onclick", "javascript:__doPostBack" +

    "('_ctl0$DataGrid1$_ctl" +

    ((Convert.ToInt32(e.Item.ItemIndex.ToString()))+2) +

    "$_ctl0','')");

    }

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

    {

    e.Item.Attributes.Add("onmouseover",

    "this.style.backgroundColor='beige';this.style.cursor='pointer'");

    e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='#D9E2FF';");

    e.Item.Attributes.Add("onclick", "javascript:__doPostBack" +

    "('_ctl0$DataGrid1$_ctl" +

    ((Convert.ToInt32(e.Item.ItemIndex.ToString()))+2) +

    "$_ctl0','')");

    }*/

    //For a single color Datagrid

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

    e.Item.ItemType == ListItemType.Item)

    {

    e.Item.Attributes.Add("onmouseover",

    "this.style.backgroundColor='beige';this.style.cursor='pointer'");

    e.Item.Attributes.Add("onmouseout",

    "this.style.backgroundColor='#99B3FF';");

    e.Item.Attributes.Add("onclick", "javascript:__doPostBack" +

    "('" + dgResults.UniqueID + "','')");

    }

    }

    public class CArrayListSearch : IComparer

    {

    public int Compare(object x,object y)

    {

    return string.Compare( x.ToString(), y.ToString(), true );

    }

    }

    public class CArrayListSort : IComparer

    {

    public int Compare(object x,object y)

    {

    return string.Compare( x.ToString(), y.ToString(), true );

    }

    }

    Elizabeth Bradley
  • Re: How to make the Datagrid rows clickable

    05-10-2007, 7:46 PM
    Answer
    • Loading...
    • djh
    • Joined on 06-09-2006, 6:08 AM
    • Posts 65

    Hi Elizabeth,

    Check out these links for more info on DataGrid/GridView row selection.

    http://aspnet.4guysfromrolla.com/articles/072104-1.aspx

    http://gridviewguy.com/ArticleDetails.aspx?articleID=188

    Hope this helps,
    David

    Filed under: , ,
  • Re: How to make the Datagrid rows clickable

    05-23-2007, 4:48 PM
    • Loading...
    • evb5145
    • Joined on 06-22-2006, 12:57 PM
    • Washington DC
    • Posts 66

    Hi,

    I followed the article on http://aspnet.4guysfromrolla.com/articles/072104-1.aspx, but I still couldnt make the row selection work. When the mouse hovers over a row, the row is highlighted (changes color). But when I click the highlighted row, nothing happens. When I run the debugger, the event handlers

    private void dgFacilities_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)

    {

    GoToFacility(e.Item.Cells[1].Text);

    }

    private void dgFacilities_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)

    {

    GoToFacility(e.Item.Cells[1].Text);

    }

    are not being called. What am I missing here?

    relevant code behind:

    public class chooseFacility : System.Web.UI.Page
          {
            protected System.Web.UI.WebControls.Panel pnlWrapper;
            protected skmDataGrid.PrettyDataGrid dgFacilities;
            protected System.Web.UI.WebControls.Button btnSearch;
            protected System.Web.UI.WebControls.TextBox txtSearch;
            protected System.Web.UI.WebControls.Label lblEnter;
            protected System.Web.UI.WebControls.Button btnChooseFacility;
            protected System.Web.UI.WebControls.TextBox txtChooseFacility;
            protected System.Web.UI.WebControls.Label lblSelect;
            protected System.Web.UI.WebControls.Label lblChooseFacility;
            protected System.Web.UI.WebControls.Panel pnlError;
            protected System.Web.UI.WebControls.Label lblError;
            protected System.Web.UI.WebControls.HyperLink hlCustomerSupport;
            protected System.Web.UI.HtmlControls.HtmlInputHidden REDIRECT;
           
            private void Page_Load(object sender, System.EventArgs e)
            {         
              if (!Page.IsPostBack)
                PopulateTable();
            }
           
            private void PopulateTable()
            {
              int i = 0;
              //((ArrayList)Cache["aUserSites"]).Sort();// .Sort(new CUserSitesSort());
              //for (i=0; i<((ArrayList)Cache["aRouteSites"]).Count; i++)
                //((ArrayList)Cache["aRouteSites"]).Sort(new CRouteSitesSort());

              DataTable dataTable = new DataTable();
              dataTable.Columns.Add("Name");
              dataTable.Columns.Add("Prov_Num");
              DataRow dataRow;
             
              for (i=0; i<((ArrayList)Cache["aRouteSites"]).Count; i++)
              {
                if (((ArrayList)Cache["aUserSites"]).BinarySearch(((string[])((ArrayList)Cache["aRouteSites"])[i])[0]) > -1)
                {             
                  // Create new row from DataTable.
                  dataRow = dataTable.NewRow();
                  dataRow["Name"] = ((string)((string[])((ArrayList)Cache["aRouteSites"])[i])[1]);
                  dataRow["Prov_Num"] = ((string)((string[])((ArrayList)Cache["aRouteSites"])[i])[0]);
                  dataTable.Rows.Add(dataRow);
                }
              }
              DataView dv = new DataView(dataTable);
              Cache["dv"] = dv;

              dgFacilities.DataSource = dataTable;
              dgFacilities.DataBind();
              pnlWrapper.Visible = true;
              pnlError.Visible = false;
            }

            public object GetSitesFromRoute(string cWhere)
            {
              int i = 0;
              string cSqlStmt = "select distinct NAME, PROV_NUM from webconfigs.route";
              ArrayList aRouteSites = new ArrayList();         
              Sql.SqlConfig oSqlCfg = Sql.loadSqlConfig("webconfigs", "route");
              if (oSqlCfg == null)
                return null;

              string connectionString = "server=" + oSqlCfg.Server + ";" +
                "user id=" + oSqlCfg.User + ";" +
                "password=" + oSqlCfg.Pass + ";" +
                "database=" + oSqlCfg.Database + ";" +
                "pooling=false;" +
                "allowzerodatetime=true";
              MySqlConnection connection = new MySqlConnection(connectionString);
              /*if (cWildcard.Length < 1)
                cSqlStmt = "select distinct NAME, PROV_NUM from webconfigs.route";
              else
                cSqlStmt = "select distinct NAME, PROV_NUM from webconfigs.route where NAME like '%" + cWildcard + "%'";*/

              cSqlStmt += cWhere;

              MySqlCommand command = new MySqlCommand(cSqlStmt, connection);
              connection.Open();
              MySqlDataReader dr = command.ExecuteReader();
              while(dr.Read())
              {
                aRouteSites.Add(new string[2]);
                //((ArrayList)aRouteSites[i]).Add( dr.GetString(dr.GetOrdinal("PROV_NUM")).Trim() );
                ((string[])aRouteSites[i])[0] = dr.GetString(dr.GetOrdinal("PROV_NUM")).Trim();
                //((ArrayList)aRouteSites[i++]).Add( dr.GetString(dr.GetOrdinal("NAME")).Trim() );
                ((string[])aRouteSites[i++])[1] = dr.GetString(dr.GetOrdinal("NAME")).Trim();
              }
              dr.Close();
              command.Dispose();
              connection.Close();
              aRouteSites.Sort(new CRouteSitesSort());
              Cache["aRouteSites"] = aRouteSites;
              return Cache["aRouteSites"];
            }

    private void btnChooseFacility_Click(object sender, System.EventArgs e)
            {
              GoToFacility(txtChooseFacility.Text.Trim());
            }

            private void btnSearch_Click(object sender, System.EventArgs e)
            {
              Cache["aRouteSites"] = GetSitesFromRoute(" where NAME like '%" + txtSearch.Text.Trim() + "%'");
              PopulateTable();         
            }

            private void  GoToFacility(string cSite)
            {
              if (this.REDIRECT == null)
                this.REDIRECT.Value = "";

              Cache["aRouteSites"] = GetSitesFromRoute(" where PROV_NUM = " + cSite);

              if (((ArrayList)Cache["aRouteSites"]).Count < 1)
              {
                lblError.Text = "The Site Number you entered is Invalid.";
                pnlWrapper.Visible = false;
                pnlError.Visible = true;
              }
              else if (((ArrayList)Cache["aRouteSites"]).Count == 1)
              {           
                int j = ((ArrayList)Cache["aUserSites"]).BinarySearch(((string[])((ArrayList)Cache["aRouteSites"])[0])[0]);
                if (((ArrayList)Cache["aUserSites"]).BinarySearch(((string[])((ArrayList)Cache["aRouteSites"])[0])[0]) > -1)
                {
                  HttpCookie cookie = new HttpCookie("SITE", cSite);
                  //cookie.Expires = DateTime.Now.AddYears(10);
                  Response.SetCookie(cookie);
                  Response.Redirect("/");
                }
                else
                {
                  lblError.Text = "Security Violation. Due to security set up, this user account does not have privileges to access this site. If you believe that you have reached this message in error please contact";
                  hlCustomerSupport.Text = "Customer Support";
                  pnlWrapper.Visible = false;
                  pnlError.Visible = true;
                }
              }
            }

    private void dgFacilities_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
            {         
              // Two way sorting LOGIC
              if( (((int)(ViewState["numberDiv"]))%2) == 0 )
                ((DataView)Cache["dv"]).Sort = e.SortExpression + " " + "ASC";
              else
                ((DataView)Cache["dv"]).Sort = e.SortExpression + " " + "DESC";
             
              ViewState["numberDiv"] = ((int)ViewState["numberDiv"]) + 1;
              dgFacilities.DataSource = ((DataView)Cache["dv"]);
              dgFacilities.DataBind();
              pnlWrapper.Visible = true;
              pnlError.Visible = false;
            }

            private void dgFacilities_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
            {
              GoToFacility(e.Item.Cells[1].Text);
            }

            private void dgFacilities_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
            {
              GoToFacility(e.Item.Cells[1].Text);
            }

            public class CRouteSitesSearch : IComparer
            {
              public int Compare(object x,object y)
              {
                return string.Compare( ((string[])x)[0].ToString(), ((string[])y)[0].ToString(), true );
              }
            }

            public class CRouteSitesSort : IComparer
            {
              public int Compare(object x,object y)
              {
                return string.Compare( ((string[])x)[0].ToString(), ((string[])y)[0].ToString(), true );
              }
            }
           

    Pls. help and thanks in advance.

    Elizabeth Bradley
  • Re: How to make the Datagrid rows clickable

    05-23-2007, 6:15 PM
    • Loading...
    • evb5145
    • Joined on 06-22-2006, 12:57 PM
    • Washington DC
    • Posts 66

    I figured out what's wrong. The following code is missing from InitializeComponent()

    this.dgFacilities.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgFacilities_ItemCreated);

    this.dgFacilities.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgFacilities_ItemCommand);

    Elizabeth Bradley
  • Re: How to make the Datagrid rows clickable

    05-23-2007, 6:57 PM
    • Loading...
    • evb5145
    • Joined on 06-22-2006, 12:57 PM
    • Washington DC
    • Posts 66

    Hi,

     Before using the PrettyDataGrid, I was using the regular DataGrid and was able to implement sorting. But I was able to make the rows clickable. So I decided to use PrettyDatagrid. Now that the problem of making the rows clickable is resolved, sorting doesnt work anymore. One would assume that since PrettyDatagrid is derived from Datagrid, sorting would still work.

    Here's where the problem is:

    In order to make the rows clickable, the code that follows was added to the codebehind:

    private void dgFacilities_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)

    {

    GoToFacility(e.Item.Cells[1].Text);

    }

    But when I click the column header to sort, the above handler is called. When that happens, e.Item.Cells[1].Text is empty and therefore an exception is thrown inside the GotoFacilitly function.

    Please help me in fixing this and thanks.

    Elizabeth Bradley
  • Re: How to make the Datagrid rows clickable

    05-23-2007, 7:31 PM
    • Loading...
    • djh
    • Joined on 06-09-2006, 6:08 AM
    • Posts 65

    Hi Elizabeth,

    You can try checking the RowType before calling 'GoToFacility'.

    You could then change the action if the RowType is 'DataControlRowType.Header'

    Not sure if this will help but it's all i can think of.

    Cheers,
    David
     

     

  • Re: How to make the Datagrid rows clickable

    05-29-2007, 4:31 PM
    • Loading...
    • evb5145
    • Joined on 06-22-2006, 12:57 PM
    • Washington DC
    • Posts 66

    I ended up putting a conditional statement:

    private void dgFacilities_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)

    {

    if (e.Item.Cells[1] == null || e.Item.Cells[1].Text.Trim() == "")

    {

    return;

    }

    else

    {

    GoToFacility(e.Item.Cells[1].Text);

    }

    }

    It slowed down the application. It will have to do for now I guess.

    Elizabeth Bradley
Page 1 of 1 (7 items)
Microsoft Communities
Page view counter