DataGrid's Strange Problem

Discussion in 'ASP .Net Web Controls' started by A DEVELOPER, Nov 13, 2004.

  1. A DEVELOPER

    A DEVELOPER Guest

    my table has total 3 columns like emp_id(primay key),emp_name emp_address
    i m populating my datagrid at run time successfully .
    now i add functionality of hotmail model(checkboxex) in it successfully
    but for this i did enhanced simple datagrid's functionality and
    add one template column and placed label on it (so that i could do deletion
    of records
    selcted by user by checkboxes when a user clik on "Delete" button .
    in label i took emp_id as field

    NOW MY PROBLEM IS

    "how can i hide my emp_id column at run time ..i need(want)
    to see only 3 columns at run time(checkbox templte column
    ,emp_name,emp_address)
    i tried DataGrid1.Columns[2].Visible=false(2 is number of emp_id)
    but it did give following error..


    Exception Details: System.ArgumentOutOfRangeException: Index was out of
    range.
    Must be non-negative and less than the size of the collection. Parameter
    name: index
    DataGrid1.Columns[2].Visible=false;<----------------(error in this
    line)
    if i dont choose emp_id in SQL Query then a new error comes in my template
    column.."Unknown Column name"
    plz sugesst me
    ACTUAL CODE IS :-
    -------------------------------------------------------------------------------------
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;

    namespace fifthpro
    {
    /// <summary>
    /// Summary description for WebForm1.
    /// </summary>
    public class WebForm1 : System.Web.UI.Page
    {
    protected System.Web.UI.WebControls.Button btnAdd;
    protected System.Web.UI.WebControls.DataGrid DataGrid1;
    public SqlConnection objConn;
    public const string ConnStr=
    "uid=sa;pwd=password;server=NEW103;database=Car_test";

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


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

    // Put user code to initialize the page here
    if(!IsPostBack)
    {
    fnFillGrid();
    }


    string jsScript = "<script language=JavaScript> "
    +" function confirmDelete (frm) {"
    +" for (i=0; i<frm.length; i++) {"
    +" if (frm.elements.name.indexOf ('DeleteThis') !=-1) {"
    +" if(frm.elements.checked) {return confirm ('Are you sure you want
    to delete your selection(s)?')}"
    +" }}}"
    +" function select_deselectAll (chkVal, idVal){"
    +" var frm = document.forms[0];"
    +" for (i=0; i<frm.length; i++) {"
    +" if (idVal.indexOf ('CheckAll') != -1) {"
    +" if(chkVal == true) { frm.elements.checked = true;"
    +" } else {"
    +" frm.elements.checked = false;"
    +" } } else if (idVal.indexOf('DeleteThis') != -1) {"
    +" if(frm.elements.checked == false) {"
    +" frm.elements[1].checked = false;"
    +" } }}}</script>";

    RegisterClientScriptBlock("clientScript", jsScript);
    WebControl button = (WebControl) Page.FindControl ("Confirm");
    button.Attributes.Add ("onclick", "return confirmDelete (this.form);");
    }


    #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);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
    this.DataGrid1.PageIndexChanged += new
    System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
    this.Load += new System.EventHandler(this.Page_Load);

    }
    #endregion


    #region "UI Layer"

    private void btnAdd_Click(object sender, System.EventArgs e)
    {
    string strCheckStatus="Add";
    Session["strCheckStatus"]=strCheckStatus;
    Response.Redirect("SetAlert.aspx");
    }

    private void fnFillGrid()
    {
    DataSet ds=new DataSet();
    ds=fnFillControls();
    DataGrid1.DataSource=ds;
    DataGrid1.Columns[2].Visible=false;

    DataGrid1.DataBind();

    foreach (DataGridItem dgi in DataGrid1.Items)
    {
    dgi.Attributes.Add("onmouseover", "this.style.backgroundColor='#ffcc99'");
    dgi.Attributes.Add("onmouseout",
    "this.style.backgroundColor='Peachpuff'");
    }
    }

    private void DataGrid1_PageIndexChanged(object source,
    System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
    DataGrid1.CurrentPageIndex=e.NewPageIndex;
    fnFillGrid();
    }
    #endregion

    #region "Business Logic"

    public DataSet fnFillControls()
    {
    //string SqlStatement="select
    AlertID,Date,Site,ComparesWith,CountryID,CityId,CarType,Figure,Variance,Compare,EmailId,CcEmailId,BCcEmailId,'<a
    target=display href=SetAlert.aspx?ALERTID'+'='+convert(varchar(10),ALERTID)+'
    >'+convert(varchar(10),SITE)+'</a>' from SetAlert";

    string SqlStatement="select Date,Site,CountryId As 'Country',CityId as
    'City',CarType,"
    +" (figure + ',' + variance+ ',' + compare) as '
    Values[Figure,Variance,Compare]',EmailId as 'Emails',"
    +" '<a target=display
    href=SetAlert.aspx?ALERTID'+'='+convert(varchar(10),ALERTID)+'"
    +" >'+'<b>DETAILS</b>'+'</a>' AS [Show Detail],AlertID from SetAlert";
    return fnGetDataSet(SqlStatement);
    }

    public void DeleteAlerts (Object sender, EventArgs e)
    {
    string dgIDs = "";
    bool BxsChkd = false;
    foreach (DataGridItem i in DataGrid1.Items)
    {
    CheckBox deleteChkBxItem = (CheckBox)i.FindControl("DeleteThis");
    if (deleteChkBxItem.Checked)
    {
    BxsChkd = true;
    dgIDs += Convert.ToInt32(((Label) i.FindControl
    ("AlertID")).Text.ToString()) + ",";
    }
    }
    string SqlStatement="delete from SetAlert where AlertID IN (" +
    dgIDs.Substring(0,dgIDs.LastIndexOf(",")) + ")";
    if (BxsChkd == true)
    {
    SqlConnection objConn1;
    const string
    ConnStr1="uid=sa;pwd=password;server=NEW103;database=CAR_TEST";
    objConn1=new SqlConnection(ConnStr1);
    string SqlStatement1="delete from SetAlert where AlertID IN (" +
    dgIDs.Substring(0,dgIDs.LastIndexOf(",")) + ")";
    if(objConn1.State==ConnectionState.Closed)
    objConn1.Open();
    SqlCommand cmd=new SqlCommand(SqlStatement1,objConn1);
    cmd.ExecuteNonQuery();
    objConn1.Close();
    fnFillGrid();
    }
    }
    #endregion

    #region "DataLayer"

    private SqlConnection fnGetConnection()
    {
    objConn=new SqlConnection(ConnStr);
    return objConn;
    }

    private string fnConnectString()
    {
    string ConnectString="uid=sa;pwd=password;server=NEW103;database=Car_test";
    return ConnectString;
    }

    public DataSet fnGetDataSet(string SqlStatement)
    {
    DataSet MyDataSet=new DataSet();
    objConn=new SqlConnection(fnConnectString());
    SqlDataAdapter da=new SqlDataAdapter(SqlStatement,objConn);
    da.Fill(MyDataSet);
    return MyDataSet;
    }

    public int fnExecuteNonQuery(string SqlStatement)
    {
    SqlConnection objConn=fnGetConnection();
    if (objConn.State==ConnectionState.Closed)
    objConn.Open();
    SqlCommand cmd=new SqlCommand(SqlStatement,objConn);
    int i=cmd.ExecuteNonQuery();
    if (objConn.State==ConnectionState.Open)
    objConn.Close();
    return i;
    }

    #endregion

    }
    }
    ------------------------------------------------------------------------------------------------
    A DEVELOPER, Nov 13, 2004
    #1
    1. Advertising

  2. A DEVELOPER

    Eric Maia Guest

    Is there some reason why you have to hide the emp_id column at
    runtime? Why not just define your emp_id column in the HTML code like
    this:

    Datagrid open tag...>
    <asp:boundcolumn DataField="emp_id" Visible="False" />
    <...rest of datagrid columns...

    Also, did you take into account that the Columns collection is
    0-based? (the first is [0],[1],[2],etc.)

    Finally, if you really need to hide it conditionally at runtime, you
    will probably need to do it using an OnItemDataBound event handler. If
    you do it before or after it's databound, it probably won't work.

    in your DataGrid tag add the event:
    OnItemDataBound="DataGrid1_ItemDataBound"

    In your code-behind, write the method to hide the column - one row at
    a time:

    protected void DataGrid1_ItemDataBound(object sender,
    DataGridItemEventArgs e)
    {
    ListItemType thisType = (ListItemType)e.Item.ItemType;
    // these types won't have the same controls - ignore them
    if (thisType == ListItemType.Header || thisType ==
    ListItemType.Separator
    || thisType == ListItemType.Footer)
    return;

    // hide the emp_id row - I am assuming here it's [2] as you said
    e.Item.Controls[2].Visible = false;
    }


    - Eric


    "A DEVELOPER" <A > wrote in message news:<>...

    >
    > NOW MY PROBLEM IS
    >
    > "how can i hide my emp_id column at run time ..i need(want)
    > to see only 3 columns at run time(checkbox templte column
    > ,emp_name,emp_address)
    > i tried DataGrid1.Columns[2].Visible=false(2 is number of emp_id)
    > but it did give following error..
    Eric Maia, Nov 19, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ron
    Replies:
    0
    Views:
    318
  2. Replies:
    2
    Views:
    453
  3. Harvey Twyman
    Replies:
    8
    Views:
    559
    August Derleth
    Oct 25, 2003
  4. Andreas Klemt
    Replies:
    0
    Views:
    292
    Andreas Klemt
    Oct 8, 2003
  5. John Walsch
    Replies:
    0
    Views:
    194
    John Walsch
    Jul 9, 2004
Loading...

Share This Page