顯示具有 CheckBox 標籤的文章。 顯示所有文章
顯示具有 CheckBox 標籤的文章。 顯示所有文章

2014年7月13日 星期日

[RESOLVED] Detailsview null value


I want to check the value in Date Shipped. If there isn't anything in it, it won't allow the user to move on to the next page. I created a Session to check, but it never has a null value. I'm not sure why.


protected void Page_Load(object sender, EventArgs e)
{
lblError.Visible = false;
ShippingError.Visible = false;
CanceledError.Visible = false;
dvAddress.Visible = false;
dvCustomer.Visible = false;

}
protected void btnPacking_Click(object sender, EventArgs e)
{
Session["OrderID"] = dvOrder.SelectedValue;

if (Session["OrderID"] != null)
{
if (Session["Shipped"] != null)
{
Response.Redirect("~/PackageManagement/Packing2.aspx");
}
else
{
ShippingError.Visible = true;
}
}

else
{
lblError.Visible = true;
}
}

protected void dvOrder_DataBound(object sender, EventArgs e)
{


if (dvOrder.SelectedValue != null)
{
Label AddressID = dvOrder.FindControl("lblAddressID") as Label;
Address.Text = AddressID.Text;
Session["Address1"] = AddressID.Text;

if (dvOrder.CurrentMode == DetailsViewMode.ReadOnly)
{
Label Shipped = dvOrder.FindControl("lblShipped") as Label;
Session["Shipped"] = Shipped.Text;


}
dvAddress.Visible = true;
dvAddress.DataBind();
}
else
{
dvAddress.Visible = false;
}

}

    











































































Maybe you need to check for empty string instead. Or use the string isnullorempty().



Try as:


protected void btnPacking_Click(object sender, EventArgs e)
{
Session["OrderID"] = dvOrder.SelectedValue;

if (!string.IsNullOrEmpty(Session["OrderID"] as string))
{
if (!string.IsNullOrEmpty(Session["Shipped"] as string))
{
Response.Redirect("~/PackageManagement/Packing2.aspx");
}
else
{
ShippingError.Visible = true;
}
}

else
{
lblError.Visible = true;
}
}

Make sure each time databound you have to clear session values, for eg assign String.Empty in Session variable




 



Thank you! That worked (although I switched it to being empty).


Here's the code:



protected void Page_Load(object sender, EventArgs e)
{
lblError.Visible = false;
ShippingError.Visible = false;
CanceledError.Visible = false;
dvAddress.Visible = false;
dvCustomer.Visible = false;

}
protected void btnPacking_Click(object sender, EventArgs e)
{
Session["OrderID"] = dvOrder.SelectedValue;

if (Session["OrderID"] != null)
{
if (string.IsNullOrEmpty(Session["Shipped"] as string))
{
ShippingError.Visible = false;
Response.Redirect("~/PackageManagement/Packing2.aspx");
}
else
{
ShippingError.Visible = true;
}
}

else
{
lblError.Visible = true;
}
}

protected void dvOrder_DataBound(object sender, EventArgs e)
{
Session["Address1"] = null;
Session["Shipped"] = null;

if (dvOrder.SelectedValue != null)
{
Label AddressID = dvOrder.FindControl("lblAddressID") as Label;
Address.Text = AddressID.Text;
Session["Address1"] = AddressID.Text;

if (dvOrder.CurrentMode == DetailsViewMode.ReadOnly)
{
Label Shipped = dvOrder.FindControl("lblShipped") as Label;

if (Shipped != null)
{
Session["Shipped"] = Shipped.Text;
}
}
dvAddress.Visible = true;
dvAddress.DataBind();
}
else
{
dvAddress.Visible = false;
}

}







[RESOLVED] calling Checkbox checked Event


I've a repeater and in repeater i've check box list..wheck is generated dynamically.


How i can call check box checked Even


here is code








<%#GetGroupName(Eval("MENU_MODIFIER_GROUP_NAME_TRANSLATION_ID").ToString().Trim())%>
[Free :
<%#GetFreeQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]   [max:

<%#GetMaxQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]






<%-- --%>
runat="server">









Set cbl Autopostback="true"


CheckedChanged event is for CheckBox instead CheckBoxList


CheckBoxList is using SelectedIndexChanged


This sample for CheckBox


    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
RepeaterItem ri = (RepeaterItem)cb.NamingContainer;
HiddenField hdngrpOpid = (HiddenField)ri.FindControl("hdngrpOpid");
int idx = ri.ItemIndex;




}












<%#GetGroupName(Eval("MENU_MODIFIER_GROUP_NAME_TRANSLATION_ID").ToString().Trim())%>
[Free :
<%#GetFreeQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]   [max:

<%#GetMaxQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]






<%-- --%>
runat="server" AutoPostBack="true" onselectedindexchanged="cbxControl_SelectedIndexChanged" >





On Code Behind
protected void cbxControl__SelectedIndexChanged(object sender, EventArgs e)
{

}


[RESOLVED] GridView column is hidden when export to excel exlcude the hidden column


I have a gridview, some of column is hidden but when i export to excel, in excel it still show the hidden column. May i know how to do it??


below is my sample script in App_Code:


public class GridViewExportUtil

{



    public static void Export(string fileName, GridView gv)

    {

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.ClearContent();

        HttpContext.Current.Response.ClearHeaders();

        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));



         using (StringWriter sw = new StringWriter())

        {

            using (HtmlTextWriter htw = new HtmlTextWriter(sw))

            {

                Table table = new Table();




                if (gv.HeaderRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);

                    table.Rows.Add(gv.HeaderRow);

                }



                foreach (GridViewRow row in gv.Rows)

                {

                    GridViewExportUtil.PrepareControlForExport(row);

                    table.Rows.Add(row);

                    

                }



                if (gv.FooterRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);

                    table.Rows.Add(gv.FooterRow);

                }



                table.RenderControl(htw);



                HttpContext.Current.Response.Write(sw.ToString());

                HttpContext.Current.Response.Flush();

                HttpContext.Current.Response.Close();

                HttpContext.Current.Response.End();

            }

        }

    }



    private static void PrepareControlForExport(Control control)

    {

        for (int i = 0; i < control.Controls.Count; i++)

        {

            Control current = control.Controls[i];

            if (current is LinkButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));

            }

            else if (current is ImageButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));

            }

            else if (current is HyperLink)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));

            }

            else if (current is DropDownList)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));

            }

            else if (current is CheckBox)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));

            }

            else if (current.Visible == false)

            {

                control.Controls.Remove(current);

            }

            if (current.HasControls())

            {

                GridViewExportUtil.PrepareControlForExport(current);

            }

        }

    }



Maybe you can do like this


GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;









oned_gk



Maybe you can do like this
GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;




Thank for your information. I have try to add in the below code, but the problem still same....any idea??

                for (int i = gv.Columns.Count - 1; i >= 0; i--)

                {

                    if (gv.Columns[i].Visible == false)

                    {

                        gv.HeaderRow.Cells[i].Visible = false;

                        gv.FooterRow.Cells[i].Visible = false;

                    }

                    gv.Columns[i].Visible = false;

                }



Hi lansishao,


I have checked your code and to me, the method PrepareControlForExport(Control control) needs some refinement, actually when u replace different controls like link-buttons, dropdowns etc with LiteralControl controls, there you should check the visibility
of the actual control, if actual control is visible then you should replace it with Literal otherwise no need to add it. Hopefully you got my point,


else if (current is CheckBox && current.Visible)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}







Thanks 



Thank for your information. But actually i no so understand what you mean. Can you provide me some sample of code? thank you.



here it is,code id Bold and and under-lined


else if (current is CheckBox && current.Visible) // visibility check
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}



Thank you...but after i try ur method add on the code, after export the data to excel, those hidden column still show....
Cry



can you share the ASPX page code, where you are hiding the grid columns, like grid item template and specially the hidden column template.


thanks



this is sample as below:




        EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="Vertical"             

        style="font-family: 'Century Gothic'; font-size: small" Width="98%" ShowFooter="True"

        OnPreRender = "gv_PreRender" OnRowDataBound = "gv_RowDataBound">

   

   

                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


   



change your hidden item template as follow,




ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Jan") %>'>


ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Feb") %>'>










thanks for you...i have set the label to visible and the problem solved..


because it have many page...may i know any best way to amend the code what i post before?



it is good to know that your problem solved, please mark the thread as answered if it helps you Innocent


Secondly, in your code you are checking at control Level that if it is visible or not, your code line


if(control.visible==false)

so you have to apply the visible attribute to every control in every grid in every page, other wise chagne the code to export data, that change of code, may introduce other problems :) 




[RESOLVED] Bind a Checkbox to a Char database type


I have this, very common I think, problem...


In the DB there is column name ENABLED which is of type char(1), and contains two "boolean" values: 'Y' or 'N'


In a FormView I want to Bind this column in a checkbox, which should be checked when the column value is 'Y', unchecked otherwise...



Up to now, I am only able to cast it correctly for displaying the value, with something like:


Checked='<%# Eval("ENABLED").ToString() == "S" ? true:false %>' 

(or using a code-behind custom function to convert the value).


The problem is when I try to Update the value, because with this code, nothing happens! (the ENABLED parameter isn't passed to the Updating function!)


And if in the above code I change Eval to Bind("ENABLED") I get this error:


Compiler Error Message: CS0103: The name 'Bind' does not exist in the current context



How can I resolve this?




Use bit field instead, you will simply Checked='<%# Eval ("ENABLED") %>' use boolean parameter type, if you want to display it as y/n use select case [enabled] when true then 'y' else 'n'

You, are right, I am calling for trouble...


But I can't change the DB column datatype, because I don't have the permission (and besides the DB is queried by other applications)



Get checkbox using updating event, then set sqldatasource1.updatepatameters("enabled").DefaultValue ="y" based checked value.

[RESOLVED] Checkboxes in my gridview being unchecked don&#39;t remove value from Dictionary


We just uncovered an odd bug in this gridview with checkboxes. (original thread:
http://forums.asp.net/post/4691898.aspx) The idea is to store the checkboxes that are checked into a dictionary that has (username, boolean) in this case the key is username, the value is boolean. As I step
through the checkbox state, I'm wanting to make it so when someone unchecks a username checkbox, it gets stripped from the checkbox dictionary. It doesn't seem to be working. I'm using the viewstate to try to keep track of which checkboxes are checked. I guess
this is what I get for trying to use GridView with paging, ugh! Here's the code:


 


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblName = ((Label)e.Row.FindControl("lblName"));
DataRowView _dv = (DataRowView)e.Row.DataItem;
UserInformation _u = new UserInformation((string)_dv.Row["USER"], false);
if (_u.Name != null)
{
lblName.Text = _u.Name;
_u = null;
}
else
{
e.Row.Visible = false;
}
String id = (String)GridView1.DataKeys[e.Row.RowIndex].Value;
if (!_checkBoxDictionary.ContainsKey(id))
{
_checkBoxDictionary.Add(id, false);
}
CheckBox checkBox = (CheckBox)e.Row.FindControl("chkSelect");
checkBox.Checked = _checkBoxDictionary[id];
}
}

protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
_checkBoxDictionary = (Dictionary)ViewState["CheckBoxDictionary"];
}

protected override object SaveViewState()
{
ViewState["CheckBoxDictionary"] = _checkBoxDictionary;
return base.SaveViewState();
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
String id = (String)GridView1.DataKeys[row.RowIndex].Value;
CheckBox checkBox = (CheckBox)row.FindControl("chkSelect");
_checkBoxDictionary[id] = checkBox.Checked;
}
}



Solved the problem with a combination of what I found there and a little of my own coding handywork. Primarily, the answer to my problem was found at

http://www.codeproject.com/Articles/202938/How-to-select-multiple-records-from-the-GridView-a


[RESOLVED] Detailsview null value


I want to check the value in Date Shipped. If there isn't anything in it, it won't allow the user to move on to the next page. I created a Session to check, but it never has a null value. I'm not sure why.


protected void Page_Load(object sender, EventArgs e)
{
lblError.Visible = false;
ShippingError.Visible = false;
CanceledError.Visible = false;
dvAddress.Visible = false;
dvCustomer.Visible = false;

}
protected void btnPacking_Click(object sender, EventArgs e)
{
Session["OrderID"] = dvOrder.SelectedValue;

if (Session["OrderID"] != null)
{
if (Session["Shipped"] != null)
{
Response.Redirect("~/PackageManagement/Packing2.aspx");
}
else
{
ShippingError.Visible = true;
}
}

else
{
lblError.Visible = true;
}
}

protected void dvOrder_DataBound(object sender, EventArgs e)
{


if (dvOrder.SelectedValue != null)
{
Label AddressID = dvOrder.FindControl("lblAddressID") as Label;
Address.Text = AddressID.Text;
Session["Address1"] = AddressID.Text;

if (dvOrder.CurrentMode == DetailsViewMode.ReadOnly)
{
Label Shipped = dvOrder.FindControl("lblShipped") as Label;
Session["Shipped"] = Shipped.Text;


}
dvAddress.Visible = true;
dvAddress.DataBind();
}
else
{
dvAddress.Visible = false;
}

}

    











































































Maybe you need to check for empty string instead. Or use the string isnullorempty().



Try as:


protected void btnPacking_Click(object sender, EventArgs e)
{
Session["OrderID"] = dvOrder.SelectedValue;

if (!string.IsNullOrEmpty(Session["OrderID"] as string))
{
if (!string.IsNullOrEmpty(Session["Shipped"] as string))
{
Response.Redirect("~/PackageManagement/Packing2.aspx");
}
else
{
ShippingError.Visible = true;
}
}

else
{
lblError.Visible = true;
}
}

Make sure each time databound you have to clear session values, for eg assign String.Empty in Session variable




 



Thank you! That worked (although I switched it to being empty).


Here's the code:



protected void Page_Load(object sender, EventArgs e)
{
lblError.Visible = false;
ShippingError.Visible = false;
CanceledError.Visible = false;
dvAddress.Visible = false;
dvCustomer.Visible = false;

}
protected void btnPacking_Click(object sender, EventArgs e)
{
Session["OrderID"] = dvOrder.SelectedValue;

if (Session["OrderID"] != null)
{
if (string.IsNullOrEmpty(Session["Shipped"] as string))
{
ShippingError.Visible = false;
Response.Redirect("~/PackageManagement/Packing2.aspx");
}
else
{
ShippingError.Visible = true;
}
}

else
{
lblError.Visible = true;
}
}

protected void dvOrder_DataBound(object sender, EventArgs e)
{
Session["Address1"] = null;
Session["Shipped"] = null;

if (dvOrder.SelectedValue != null)
{
Label AddressID = dvOrder.FindControl("lblAddressID") as Label;
Address.Text = AddressID.Text;
Session["Address1"] = AddressID.Text;

if (dvOrder.CurrentMode == DetailsViewMode.ReadOnly)
{
Label Shipped = dvOrder.FindControl("lblShipped") as Label;

if (Shipped != null)
{
Session["Shipped"] = Shipped.Text;
}
}
dvAddress.Visible = true;
dvAddress.DataBind();
}
else
{
dvAddress.Visible = false;
}

}







[RESOLVED] calling Checkbox checked Event


I've a repeater and in repeater i've check box list..wheck is generated dynamically.


How i can call check box checked Even


here is code








<%#GetGroupName(Eval("MENU_MODIFIER_GROUP_NAME_TRANSLATION_ID").ToString().Trim())%>
[Free :
<%#GetFreeQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]   [max:

<%#GetMaxQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]






<%-- --%>
runat="server">









Set cbl Autopostback="true"


CheckedChanged event is for CheckBox instead CheckBoxList


CheckBoxList is using SelectedIndexChanged


This sample for CheckBox


    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
RepeaterItem ri = (RepeaterItem)cb.NamingContainer;
HiddenField hdngrpOpid = (HiddenField)ri.FindControl("hdngrpOpid");
int idx = ri.ItemIndex;




}












<%#GetGroupName(Eval("MENU_MODIFIER_GROUP_NAME_TRANSLATION_ID").ToString().Trim())%>
[Free :
<%#GetFreeQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]   [max:

<%#GetMaxQuantity(Eval("MENU_MODIFIER_GROUP_ID").ToString().Trim())%>
]






<%-- --%>
runat="server" AutoPostBack="true" onselectedindexchanged="cbxControl_SelectedIndexChanged" >





On Code Behind
protected void cbxControl__SelectedIndexChanged(object sender, EventArgs e)
{

}


[RESOLVED] GridView column is hidden when export to excel exlcude the hidden column


I have a gridview, some of column is hidden but when i export to excel, in excel it still show the hidden column. May i know how to do it??


below is my sample script in App_Code:


public class GridViewExportUtil

{



    public static void Export(string fileName, GridView gv)

    {

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.ClearContent();

        HttpContext.Current.Response.ClearHeaders();

        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));



         using (StringWriter sw = new StringWriter())

        {

            using (HtmlTextWriter htw = new HtmlTextWriter(sw))

            {

                Table table = new Table();




                if (gv.HeaderRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);

                    table.Rows.Add(gv.HeaderRow);

                }



                foreach (GridViewRow row in gv.Rows)

                {

                    GridViewExportUtil.PrepareControlForExport(row);

                    table.Rows.Add(row);

                    

                }



                if (gv.FooterRow != null)

                {

                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);

                    table.Rows.Add(gv.FooterRow);

                }



                table.RenderControl(htw);



                HttpContext.Current.Response.Write(sw.ToString());

                HttpContext.Current.Response.Flush();

                HttpContext.Current.Response.Close();

                HttpContext.Current.Response.End();

            }

        }

    }



    private static void PrepareControlForExport(Control control)

    {

        for (int i = 0; i < control.Controls.Count; i++)

        {

            Control current = control.Controls[i];

            if (current is LinkButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));

            }

            else if (current is ImageButton)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));

            }

            else if (current is HyperLink)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));

            }

            else if (current is DropDownList)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));

            }

            else if (current is CheckBox)

            {

                control.Controls.Remove(current);

                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));

            }

            else if (current.Visible == false)

            {

                control.Controls.Remove(current);

            }

            if (current.HasControls())

            {

                GridViewExportUtil.PrepareControlForExport(current);

            }

        }

    }



Maybe you can do like this


GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;









oned_gk



Maybe you can do like this
GridView1.AllowSorting = false;
GridView1.Columns[2].Visible = false;
//export process
GridView1.Visible = true;
GridView1.AllowSorting = true;




Thank for your information. I have try to add in the below code, but the problem still same....any idea??

                for (int i = gv.Columns.Count - 1; i >= 0; i--)

                {

                    if (gv.Columns[i].Visible == false)

                    {

                        gv.HeaderRow.Cells[i].Visible = false;

                        gv.FooterRow.Cells[i].Visible = false;

                    }

                    gv.Columns[i].Visible = false;

                }



Hi lansishao,


I have checked your code and to me, the method PrepareControlForExport(Control control) needs some refinement, actually when u replace different controls like link-buttons, dropdowns etc with LiteralControl controls, there you should check the visibility
of the actual control, if actual control is visible then you should replace it with Literal otherwise no need to add it. Hopefully you got my point,


else if (current is CheckBox && current.Visible)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}







Thanks 



Thank for your information. But actually i no so understand what you mean. Can you provide me some sample of code? thank you.



here it is,code id Bold and and under-lined


else if (current is CheckBox && current.Visible) // visibility check
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
// Controls has been replace with Literal and Literal is alwasy Visible :)
else if (current.Visible == false)
{
control.Controls.Remove(current);
}



Thank you...but after i try ur method add on the code, after export the data to excel, those hidden column still show....
Cry



can you share the ASPX page code, where you are hiding the grid columns, like grid item template and specially the hidden column template.


thanks



this is sample as below:




        EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="Vertical"             

        style="font-family: 'Century Gothic'; font-size: small" Width="98%" ShowFooter="True"

        OnPreRender = "gv_PreRender" OnRowDataBound = "gv_RowDataBound">

   

   

                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


                   
                        ItemStyle-HorizontalAlign="Right"/>

                       

                       

                           

                       


                       


   



change your hidden item template as follow,




ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Jan") %>'>


ItemStyle-HorizontalAlign="Right"/>


Visible = "false" runat="server" Text='<%#Eval("Feb") %>'>










thanks for you...i have set the label to visible and the problem solved..


because it have many page...may i know any best way to amend the code what i post before?



it is good to know that your problem solved, please mark the thread as answered if it helps you Innocent


Secondly, in your code you are checking at control Level that if it is visible or not, your code line


if(control.visible==false)

so you have to apply the visible attribute to every control in every grid in every page, other wise chagne the code to export data, that change of code, may introduce other problems :) 




[RESOLVED] Bind a Checkbox to a Char database type


I have this, very common I think, problem...


In the DB there is column name ENABLED which is of type char(1), and contains two "boolean" values: 'Y' or 'N'


In a FormView I want to Bind this column in a checkbox, which should be checked when the column value is 'Y', unchecked otherwise...



Up to now, I am only able to cast it correctly for displaying the value, with something like:


Checked='<%# Eval("ENABLED").ToString() == "S" ? true:false %>' 

(or using a code-behind custom function to convert the value).


The problem is when I try to Update the value, because with this code, nothing happens! (the ENABLED parameter isn't passed to the Updating function!)


And if in the above code I change Eval to Bind("ENABLED") I get this error:


Compiler Error Message: CS0103: The name 'Bind' does not exist in the current context



How can I resolve this?




Use bit field instead, you will simply Checked='<%# Eval ("ENABLED") %>' use boolean parameter type, if you want to display it as y/n use select case [enabled] when true then 'y' else 'n'

You, are right, I am calling for trouble...


But I can't change the DB column datatype, because I don't have the permission (and besides the DB is queried by other applications)



Get checkbox using updating event, then set sqldatasource1.updatepatameters("enabled").DefaultValue ="y" based checked value.

[RESOLVED] Checkboxes in my gridview being unchecked don&#39;t remove value from Dictionary


We just uncovered an odd bug in this gridview with checkboxes. (original thread:
http://forums.asp.net/post/4691898.aspx) The idea is to store the checkboxes that are checked into a dictionary that has (username, boolean) in this case the key is username, the value is boolean. As I step
through the checkbox state, I'm wanting to make it so when someone unchecks a username checkbox, it gets stripped from the checkbox dictionary. It doesn't seem to be working. I'm using the viewstate to try to keep track of which checkboxes are checked. I guess
this is what I get for trying to use GridView with paging, ugh! Here's the code:


 


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblName = ((Label)e.Row.FindControl("lblName"));
DataRowView _dv = (DataRowView)e.Row.DataItem;
UserInformation _u = new UserInformation((string)_dv.Row["USER"], false);
if (_u.Name != null)
{
lblName.Text = _u.Name;
_u = null;
}
else
{
e.Row.Visible = false;
}
String id = (String)GridView1.DataKeys[e.Row.RowIndex].Value;
if (!_checkBoxDictionary.ContainsKey(id))
{
_checkBoxDictionary.Add(id, false);
}
CheckBox checkBox = (CheckBox)e.Row.FindControl("chkSelect");
checkBox.Checked = _checkBoxDictionary[id];
}
}

protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
_checkBoxDictionary = (Dictionary)ViewState["CheckBoxDictionary"];
}

protected override object SaveViewState()
{
ViewState["CheckBoxDictionary"] = _checkBoxDictionary;
return base.SaveViewState();
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
String id = (String)GridView1.DataKeys[row.RowIndex].Value;
CheckBox checkBox = (CheckBox)row.FindControl("chkSelect");
_checkBoxDictionary[id] = checkBox.Checked;
}
}



Solved the problem with a combination of what I found there and a little of my own coding handywork. Primarily, the answer to my problem was found at

http://www.codeproject.com/Articles/202938/How-to-select-multiple-records-from-the-GridView-a


[RESOLVED] Insert Data From GridView to DB based on selected column and row


Hye I have extract data from excel sheet into DataTable and then bind it to gridview. The problem i only want to insert the wanted data from gridview into database. Refer image below


Example




For example i only want the data on the row and column that the checkbox is ticked to insert into database. So is that possible or is anyone have other suggestion to solve this problem..






urenjoy



refer following thread:


http://stackoverflow.com/questions/16801493/insert-data-of-selected-gridview-checkboxes-values-using-c-sharp-asp-net





Thanks for the reply urenjoy but the thread is only about how to selected item based on selected row only but i want to retrieve the data based on selected row and also the column..It is like array but i did not know how to get the data based on row and
column. Do you have any better idea?



hi,


You can define head template with a checkbox and in code behind to check row checkbox and column box.


such as :





ForeColor="White" />

runat="server" />





ForeColor="White" />




Text="StudentName"
runat="server" />



ForeColor="White" />




Text="Score"
runat="server" />





 protected void Button6_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Score", typeof(int));

foreach (GridViewRow c in GridView2.Rows)
{
CheckBox ckRow = (CheckBox)c.FindControl("CKSelect");//find row checkbox
if (ckRow.Checked)
{
foreach (DataControlField d in GridView2.Columns)
{
DataRow dr = dt.NewRow();

CheckBox ckColName = (CheckBox)GridView2.HeaderRow.FindControl("ShowName");// find column checkbox
CheckBox ckColScore = (CheckBox)GridView2.HeaderRow.FindControl("ShowScore");
Label lbName = (Label)c.FindControl("lbName");
Label lbScore = (Label)c.FindControl("lbScore");
if (ckColName.Checked)
{
dr["Name"] = lbName.Text;
}
if (ckColScore.Checked)
{
dr["Score"] = lbScore.Text;
}
dt.Rows.Add(dr);
}
}
}
}

Hope this helps





[RESOLVED] string query for gridview








Height="335px"

style="font-size: medium; margin-right: 0px;" Width="805px"

AllowPaging="True"

onselectedindexchanged="GridView1_SelectedIndexChanged">





















HeaderText="Name" DataField="EMP_NAME" />


HeaderText="Employee Code" DataField="employee_code" />


HeaderText="PF NO" DataField="PF_NO" />




DataField="dol" />


DataField="F_NAME" />


DataField="DOB" />


DataField="SEX" />


DataField="rol" />
















































onclick="generate_Click" />









I have bound it to the database. I want to access its  values in another page.


When i check a row and click generate it should  be accessible in other pages as well.


 I was using the followin in .cs page:


protected void generate_Click(object sender, EventArgs e)

{

foreach (GridViewRow row in GridView1.Rows)

{


CheckBox chkBx = (CheckBox)row.FindControl("chk");


if (chkBx.Checked && chkBx!=null)

{

Response.Redirect(string.Format("covering_expn.aspx?name=" + row.Cells[1].Text));

}


}


grdveiw();


 But its not accepting the parameters in the other page...Please help.



You can't access its value in the another page directly.


You have to use session variable to store its value.


Regards,



set breakpoint on this line and check value of row.Cells[1].Text... is it non empty string?


Response.Redirect(string.Format("covering_expn.aspx?name=" + row.Cells[1].Text));


if yes, u can try this


Response.Redirect("covering_expn.aspx?name=" + row.Cells[1].Text);


hope this helps...



Hi,


I hope you want to try get the parameter value of "name" query string.


First please check that "row.cells[1].text" return a non empty string.


Hope this helps


Thanks!!



Thank you all...Laughing



how to access them in another page?



i think you want to read just the Query-Stirng parameter, that you have just set in first page?


// Page_Load event of second page

var param = Request.QueryString["name"];

then follow the above code. thanks 




[RESOLVED] Enable field sorting when gridview datasource from code behind


Ok, I'm not sure how to get this to work. I have a gridview and I've enabled paging and sorting on my gridview. I set the two fields in question to be sortable headers. Here is what I have so far:


 


// Populate GridView using data table from code behind

private void GetData()
{
DataTable table = new DataTable();
// get the connection
string _cs = DBUtils.DBString;
using (SqlConnection conn = new SqlConnection(_cs))
{
// write the sql statement to execute
string sql = "SELECT [userid], [department] FROM [Employees] order by userid";
// instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
// get the adapter object and attach the command object to it
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
// fire Fill method to fetch the data and fill into DataTable
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}

// now for the code that is for sorting, I think this may be my problem.

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = GridView1.DataSource as DataTable;

if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

GridView1.DataSource = dataView;
GridView1.DataBind();
}
}

// this code determines the selected sort order

private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;

switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;

case SortDirection.Descending:
newSortDirection = "DESC";
break;
}

return newSortDirection;
}



So, how do I get this sorting to work?



dataView. Sort = e. SortExpression + " " + ConvertSortDirectionToSql (e. SortDirection ); AFAIK, dv.sort= like : dataView. Sort = e. SortExpression + " Asc"

hi,


let the sorting work contains several steps:


1)set AllowSorting="True".


2)add SortExpression property in field.like:



3)define gridview sorting method.


Hope this helps



I'm using template fields not bound fields.



Ok, once I click the header, it sets the sort direction as ascending and retains that value no matter how many times I click on the header.



Hi,


You can use client side sorting mechanism. Refer the below urls which will use tablesorter & jquery for this because if we are doing it in server side we need to either fetch the data from db again or we need to keep it in session/other storage mechanism
for holding the data source of gridview won't be available on postback


http://dotnet-mcts.jecaestevez.com/2011/03/sort-aspnet-gridview-columns-using.html


http://www.iamraghuveer.com/2012/04/sorting-aspnet-gridview-control-using.html


Hope it helps




I finally figured this one out. Here's the link that helped me.


http://satindersinght.blogspot.com/2013/05/gridview-sorting-on-header-click-with.html


My relevant code sample:


 


protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
List list = new List();
if (ViewState["SelectedRecords"] != null)
{
list = (List)ViewState["SelectedRecords"];
}
foreach (GridViewRow row in GridView1.Rows)
{
String id = (String)GridView1.DataKeys[row.RowIndex].Value;
CheckBox checkBox = (CheckBox)row.FindControl("chkSelect");
if (checkBox.Checked)
{
if (!list.Contains(id))
{
list.Add(id);
}
}
if (!checkBox.Checked)
{
list.Remove(id);
}
}
ViewState["SelectedRecords"] = list;
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = Session["objects"];
GridView1.DataBind();
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GetData();
DataTable sourceTable = GridView1.DataSource as DataTable;
string sortingDirection = string.Empty;
if (direction == SortDirection.Ascending)
{
direction = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
direction = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(sourceTable);
sortedView.Sort = e.SortExpression + " " + sortingDirection;
Session["objects"] = sortedView;
DataView view = new DataView(sourceTable);
GridView1.DataSource = sortedView;
GridView1.DataBind();
}

public SortDirection direction
{
get
{
if (ViewState["directionState"] == null)
{
ViewState["directionState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["directionState"];
}
set
{ ViewState["directionState"] = value; }
}


[RESOLVED] Insert Data From GridView to DB based on selected column and row


Hye I have extract data from excel sheet into DataTable and then bind it to gridview. The problem i only want to insert the wanted data from gridview into database. Refer image below


Example




For example i only want the data on the row and column that the checkbox is ticked to insert into database. So is that possible or is anyone have other suggestion to solve this problem..






urenjoy



refer following thread:


http://stackoverflow.com/questions/16801493/insert-data-of-selected-gridview-checkboxes-values-using-c-sharp-asp-net





Thanks for the reply urenjoy but the thread is only about how to selected item based on selected row only but i want to retrieve the data based on selected row and also the column..It is like array but i did not know how to get the data based on row and
column. Do you have any better idea?



hi,


You can define head template with a checkbox and in code behind to check row checkbox and column box.


such as :





ForeColor="White" />

runat="server" />





ForeColor="White" />




Text="StudentName"
runat="server" />



ForeColor="White" />




Text="Score"
runat="server" />





 protected void Button6_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Score", typeof(int));

foreach (GridViewRow c in GridView2.Rows)
{
CheckBox ckRow = (CheckBox)c.FindControl("CKSelect");//find row checkbox
if (ckRow.Checked)
{
foreach (DataControlField d in GridView2.Columns)
{
DataRow dr = dt.NewRow();

CheckBox ckColName = (CheckBox)GridView2.HeaderRow.FindControl("ShowName");// find column checkbox
CheckBox ckColScore = (CheckBox)GridView2.HeaderRow.FindControl("ShowScore");
Label lbName = (Label)c.FindControl("lbName");
Label lbScore = (Label)c.FindControl("lbScore");
if (ckColName.Checked)
{
dr["Name"] = lbName.Text;
}
if (ckColScore.Checked)
{
dr["Score"] = lbScore.Text;
}
dt.Rows.Add(dr);
}
}
}
}

Hope this helps