Checkbox OnCheckedChange event with postback? - c#

I have a gridview with checkbox controls as columns and with Autopostback='true' for inserting to db.
Everyting works fine except when i "change pages" - Postback (?)
My checked checkboxes gets unchecked when I go back to the page.
My Page_Load have a !IsPostBack and then i bound my gridview (gwPlanning)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridViewPlanning();
}
}
and my code behind:
protected void myCheckBox_OnCheckedChange(object sender, EventArgs e)
{
CheckBox myCheckBox = (CheckBox)sender;
GridViewRow row = (GridViewRow)myCheckBox.NamingContainer;
string ThisWeekMinus2 = row.Cells[1].Text;
bool status = myCheckBox.Checked;
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("UPDATE [BI_Planning].[dbo].[tblPlanning] SET [This Week - 2] = #IsActive WHERE ActivityID = #ID ", con);
cmd.Parameters.Add("#IsActive", SqlDbType.Bit).Value = myCheckBox.Checked;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ThisWeekMinus2;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
any idea what i'm missing?

The solution was just to add:
Checked='<%#Convert.ToBoolean(Eval("....YourColumn...."))%>
<asp:CheckBox ID="CheckBox1" AutoPostBack="true" Checked='<%#Convert.ToBoolean(Eval("....YourColumn...."))%> OnCheckedChanged="myCheckBox_OnCheckedChange" runat="server" Style="text-align: center" />

Related

Filling the default value of a dropdown in a gridview with the current value

After some lengthy experimentation, I discovered that having this line of code on the aspx side:
<EditItemTemplate>
<asp:DropDownList ID="ddl_Project_Owner" runat="server" Width="70px"
DataTextField="Project_Owner" DataValueField="Project_Owner"
SelectedValue='<%# Bind("Project_Owner") %>' >
</asp:DropDownList>
</EditItemTemplate>
caused an index error, but removing the SelectedValue='<%# Bind("Project_Owner") %>' piece allowed the gridview to function properly. The only thing is, when the row goes into edit mode, the dropdown is not filled with the current value. It's blank. I'd like to fill it with the current value.
On the code-behind side, I use this code to fill the dropdown:
protected void DataGrid_ResourceAllocation_EditCommand(object sender, GridViewEditEventArgs e)
{
DataGrid_ResourceAllocation.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
DataGrid_ResourceAllocation.EditIndex = e.NewEditIndex;
LoadResourceAllocationGrid();
//DataGrid_ResourceAllocation.DataBind();
SqlConnection conn = GetConnection();
int RAC = DataGrid_ResourceAllocation.Rows.Count;
GridViewRow row = DataGrid_ResourceAllocation.Rows[e.NewEditIndex];
//*********************************************************
//******** Fill in all your dropdown lists here ***********
//*********************************************************
DropDownList ddList = row.FindControl("ddl_Project_Owner") as DropDownList;
string ddListVal = ddList.SelectedValue;
//DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_Project_Owner");
if (ddList != null)
{
//bind dropdown-list
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
//DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = ddListVal;
}
}
I tried that "ddListVal" variable because I thought it might work, but it didn't, so you can ignore that.
Can anyone help me get my dropdown to populate with the current value that exists for that field in that record?
This error is due to this : you set selectedValeue befor binding dropdownlist.
you can bind dropdownlist in RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddList= e.Row.FindControl("ddl_Project_Owner") as DropDownList;
if (ddList != null)
{
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
}
}
}

Header DDL in Gridview on ispostback

I have a header DDL in my gridview that for some reason does not keep my selected value but rather binds the gridview and the header back to "starting position"
In my DDL header for Priority i have selected value '99' but after that my header gets back to starting position of my ListItem (that is Priority)
<HeaderTemplate>
<asp:DropDownList ID="ddlPriorityHeader" AutoPostBack="True" AppendDataBoundItems="True" OnSelectedIndexChanged="ddlHeader_SelectedIndexChanged" runat="server">
<asp:ListItem>Priority</asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
I have a RowDatabound for the gridview but there i do nothing more then find the DDL for the header and then bound the DDL.
protected void gwActivity_RowDataBound(object sender, GridViewRowEventArgs e)
{
//.............. some code.....//
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT DISTINCT [Priority] FROM [BI_Planning].[dbo].[tblPriority]", con);
con.Open();
ddlPriority.DataSource = cmd.ExecuteReader();
ddlPriority.DataTextField = "Priority";
ddlPriority.DataBind();
}
}
I have put my gridview in a method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewActivity();
}
}
Can it be that im bounding my DDL everytime for my gridview? im stuck here....
You need to store ddlPriority selected text in temp place like ViewState that will keep value between postbacks.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["PriorityText"] = "Priority";
BindGridviewActivity();
}
}
And aftrt ddlPriority.DataBind(); set selectd text to ViewState value
ddlPriority.Items.FindByText(ViewState["PriorityText"].ToString()).Selected = true;
And in your ddlHeader_SelectedIndexChanged set ViewState to selected text
protected void ddlHeader_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlHeader = (DropDownList)sender;
ViewState["PriorityText"] = ddlHeader.SelectedItem.Text;
}
Check this complete example for more details

asp.net dropdownlist first selection does not fire SelectedIndexChanged event

I've created a dropdownlist, and tried clicking on the first selection but there was no firing of the SelectedIndexChanged event. However, it worked perfectly fine for the rest of the options in the dropdownlist.
Here are my codes:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string member = (String)Session["ssmem"];
if (!IsPostBack)
{
if (Session["ssmem"] == null)
Response.Redirect("LoginforAccess.aspx");
else
{
Response.ClearHeaders();
Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
Response.AddHeader("Pragma", "no-cache");
//if go back then must log in --2
}
//Dropdownlist
string strConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
//STEP1 : Define a connection to Database
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strcommand = "Select Username from [User] WHERE (UsergroupID = (SELECT UsergroupID FROM [User] AS User_1 WHERE (Username = #user)))";
SqlCommand cmd = new SqlCommand(strcommand, myConnect);
// cmd.Parameters.AddWithValue("#usergrp", groupid);
cmd.Parameters.AddWithValue("#user", member);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
DropDownList1.DataSource = reader;
DropDownList1.DataTextField = "Username";
DropDownList1.DataValueField = "Username";
DropDownList1.DataBind();
reader.Close();
myConnect.Close();
}
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Session["ssmem"] != null)
MasterPageFile = "User.master";
//change the master page --1
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//chosen name to display stats
string choseuser = "";
choseuser = DropDownList1.SelectedItem.Text;
Response.Redirect("Substats.aspx?choseuser=" + choseuser);
}
}
Source view for dropdownlist:
<asp:DropDownList ID="DropDownList1" runat="server" Width="200px" Height="35px"
AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"
ViewStateMode="Enabled">
</asp:DropDownList>
We have to add first item as title to the dropdownlist,
and instead of using datasource used dr.Read() in while loop for adding the items on dropdownlist.
This problem occurs because in dropdownlist first item is selected bydefault and it is not reflected on selection
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" ViewStateMode="Enabled">
<asp:ListItem>Select College</asp:ListItem>
<!--Add one item as title into dropdownlist in edit item of dropdownlist-->
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("hello");
try
{
string sel = "select name from websites";
SqlCommand cmd = new SqlCommand(sel,con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
/* DropDownList1.DataSource = dr;
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();*/
while (dr.Read())//used dr.read() instead of datasource
{
DropDownList1.Items.Add(dr["name"].ToString());
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("select url from websites where name = #itm", con);
cmd.Parameters.AddWithValue("#itm", DropDownList1.SelectedItem.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
Response.Redirect(dr["url"].ToString());
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}

How to disable a link button in gridview when clicked

I have two LinkButton's called Approve and Reject in my GridView and I want my Approve LinkButton to be Disabled when click on it. I tried the following code but it's not working.
protected void gvManagerTimeSheet_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ApproveRow")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
LinkButton lnkbtn = (LinkButton)row.FindControl("lbApprove");
lnkbtn.Enabled = false;
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int TimeSheetId = Convert.ToInt32(e.CommandArgument);
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spApproveTimeSheet ", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TimeSheetId", TimeSheetId);
con.Open();
cmd.ExecuteNonQuery();
GetManagerTimeSheets();
}
}
}
Well you haven't shown your aspx link button so i assuming that your link button is this
<asp:LinkButton id="linkBtn" runat="server" text="Approve" OnClientClick="Disable(this);"/>
Now you should add a javascript function like this on the page::
<script>
function Disable(link)
{
link.disabled = result;
}
</script>
Now when you click on the page your button will get disabled.
try this
LinkButton lbApprove = (LinkButton)e.Row.Cells[0].Controls[0];
You need to Rebind the grid with disabled control, but also you need to check the status in itembound event and disable. For that you can use session or hidden field.
protected void rg_OnItemCommand(object source, GridCommandEventArgs e)
{
// your logic
hdFlag.value = "val" // id of the data item to hide if more than one use array
// rebind logic for gird
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
if(hdFlag.value == "id")
{
// Find the control and hide
}
}

GridView RowUpdating returns old values after PostBack

I got a problem with my GridView. When I try to edit my GridView, I only get the old values in return.
Here's the RowUpdating event:
protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox nVorname = (TextBox)row.FindControl("newVorname");
TextBox nNachname = (TextBox)row.FindControl("newNachname");
TextBox nTelnr = (TextBox)row.FindControl("newTelnr");
TextBox nEmail = (TextBox)row.FindControl("newEmail");
HiddenField tid = (HiddenField)row.FindControl("id");
grid.EditIndex = -1;
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("update dasOertliche set vorname= #vorname, nachname=#nachname, telefonnr =#telnr, email =#email where id = #id", sqlConn);
cmd.Parameters.Add("#vorname", SqlDbType.VarChar);
cmd.Parameters["#vorname"].Value = nVorname;
cmd.Parameters.Add("#nachname", SqlDbType.VarChar);
cmd.Parameters["#nachname"].Value = nNachname.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters["#email"].Value = nEmail.Text;
cmd.Parameters.Add("#telnr", SqlDbType.VarChar);
cmd.Parameters["#telnr"].Value = nTelnr.Text;
cmd.Parameters.Add("#id", SqlDbType.Int);
cmd.Parameters["#id"].Value = tid.Value;
cmd.ExecuteNonQuery();
sqlConn.Close();
bind();
}
The TemplateField from the .aspx:
<Columns>
<asp:TemplateField HeaderText = "Vorname">
<ItemTemplate> <%#Eval ("vorname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="newVorname" runat="server" Text='<%#Eval ("vorname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</columns>
And my GridView code:
<asp:GridView runat="server" ID="grid" BorderWidth="0px" CellPadding="10"
CellSpacing="10" HorizontalAlign="Center" AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True" onrowcancelingedit="grid_RowCancelingEdit"
onrowediting="grid_RowEditing" onrowupdating="grid_RowUpdating"
AutoGenerateColumns="False">
Like I said, it always returns the old values. Any suggestions?
My Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
My bind():
public void bind()
{
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlDataAdapter sqlComm = new SqlDataAdapter("SELECT id, vorname AS 'Vorname', nachname AS 'Nachname', telefonnr, email AS 'E-Mail' FROM dasOertliche ORDER BY nachname ASC", sqlConn);
DataSet ds = new DataSet();
sqlComm.Fill(ds, "dasOertliche");
grid.DataSource = ds.Tables[0];
grid.DataBind();
sqlConn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
is wrong.
It should be:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
On Pageload put your bind grid code in following condition
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
You need to call GridView1.DataBind() in the end.

Categories

Resources