How to prevent page to scroll to top after gridview checkbox changed - c#

enter image description herei tried many solutions before to prevent page scroll top after checkbox in grid view was changed but no one solve my problem .. please help!
thanks in advance
(update)-->
this is the Design code:
<asp:Panel ID="Panel2" runat="server" CssClass="Panel" GroupingText="<img src='Images/lightbulb.gif' /> Step 2: Seclect Threats to detect">
<%--<h1 style="text-align:right;padding-right:30px;position:absolute;right:40px;top:300px" > <asp:Label ID="lbl_cost" runat="server" Text="0 $" ></asp:Label></h1>--%>
<ajax:TabContainer ID="tc_thread_types" runat="server" AutoPostBack="true" Width="100%" CssClass="Tab" ActiveTabIndex="0">
<ajax:TabPanel ID="tab_mem_threads" runat="server" HeaderText="Member Threats" CssClass="Tab">
<ContentTemplate>
<div id="scrollDiv1" style="width: 100%; max-height: 400px; overflow: auto" >
<asp:GridView ID="gv_ThDetails_Mem" runat="server" CssClass="Grid"
Style="width: 100%; padding: 25px; margin-top: 10px; margin-bottom: 10px"
AutoGenerateColumns="False" OnRowDataBound="gv_ThDetails_mem_RowDataBound">
<Columns>
<asp:BoundField DataField="thread_id" HeaderText="Threat Id" />
<asp:BoundField DataField="thread_desc" HeaderText="Threat Description" />
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="ch_all_mem" runat="server" AutoPostBack="true" OnCheckedChanged="ch_all_mem_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<%--<asp:CheckBox ID="cb_includedThreat_mem1" Onclick='<%# "ShowCurrentTime(" +Eval("serial") + " );" %>' runat="server" />--%>
<asp:CheckBox ID="cb_includedThreat_mem" runat="server" AutoPostBack="true" OnCheckedChanged="cb_includedThreat_mem_CheckedChanged" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="serial" HeaderText="serial" Visible="false" />
</Columns>
</asp:GridView>
</div>
<script type="text/javascript">
//var prm = Sys.WebForms.PageRequestManager.getInstance();
//prm.add_beginRequest(beginRequest);
//function beginRequest() {
// prm._scrollPosition = null;
//}
</script>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
And this is the code behind:
protected void cb_includedThreat_mem_CheckedChanged(object sender, EventArgs e)
{
try
{
//up_frdSetup.Update();
CheckBox included = (CheckBox)sender;
//GridViewRow gr = (GridViewRow)included.Parent.Parent;
int count;
if (rbl_memType.SelectedIndex == -1)
{
included.Checked = false;
SystemMsg.fn_SetMessageProperties("U6", "You should select membership first!"); // casting
SystemMsg.Focus();
return;
}
if (Session["IsExpired"] != null && Session["IsExpired"].ToString().Equals("Y") && rbl_memType.SelectedValue.ToString().Equals("T"))
{
included.Checked = false;
ib_save.Enabled = false;
// ib_save.CssClass = "btn disabled";
ib_save.ToolTip = "Submit was disabled As your trial version was expired!";
SystemMsg.fn_SetMessageProperties("U6", "Your trial version was expired! Please select Preimuim Subscription Now!");
//lbl_cln_msg.Text = "Your trial version was expired! Please select Premium Subscription Now!";
//cln_msg.Style.Add("display", "normal");
return;
}
if (ViewState["cnt_th_mem"] == null)
{
count = 0;
}
else
{
count = int.Parse(ViewState["cnt_th_mem"].ToString());
}
if (included.Checked)
{
count++;
ViewState["cnt_th_mem"] = count;
}
else if (!included.Checked && count > 0)
{
count--;
ViewState["cnt_th_mem"] = count;
}
included.Focus();
if (rbl_memType.SelectedValue.ToString().Equals("T"))
{
int tot_cnt = fn_check_tot_checked_threads();
if (tot_cnt > 3)
{
included.Checked = false;
count--;
ViewState["cnt_th_mem"] = count;
//lbl_cln_msg.Text = "The Maximum allowed threats in trial membership is Three only!";
//cln_msg.Style.Add("display", "normal");
SystemMsg.fn_SetMessageProperties("U6", "The Maximum allowed threats in trial membership is Three only!");
SystemMsg.Focus();
return;
}
//lbl_cost.Text = "0$";
//ViewState["cnt_th_mem"] = 0;
}
else if (rbl_memType.SelectedValue.ToString().Equals("P"))
{
//lbl_cost.Text = (Double.Parse(Session["th_price"].ToString()) * count) + "$";
ViewState["cnt_th_mem"] = count;
}
//fn_checkIncluded_Mem_Threads();
CheckBox ch_all = gv_ThDetails_Mem.HeaderRow.FindControl("ch_all_mem") as CheckBox;
if (count == gv_ThDetails_Mem.Rows.Count)
{
ch_all.Checked = true;
}
else if (count == 0)
{
ch_all.Checked = false;
}
else
{
ch_all.Checked = false;
}
fn_check_tot_cost();
}
catch (System.IO.IOException eio)
{
SystemMsg.fn_SetMessageProperties("S1", eio.Message); // IO
SystemMsg.Focus();
return;
}
catch (NullReferenceException ex)
{
SystemMsg.fn_SetMessageProperties("S2", ex.Message); // NULL
SystemMsg.Focus();
return;
}
catch (SqlException sqlEx)
{
SystemMsg.fn_SetMessageProperties("S4", sqlEx.Message); // SQL
SystemMsg.Focus();
return;
}
catch (Exception exe)
{
SystemMsg.fn_SetMessageProperties("S0", exe.Message);
SystemMsg.Focus();
return;
}
}
thanks in advance ..

Put this in the page directive <%# Page %>
MaintainScrollPositionOnPostback = "true"
It happens due to page PostBack. The above ensures the position of the scroll after page PostBack.
Or keep the GridView in a div and use JavaScript trick to do so: Maintain Scroll Position in Div

Related

How can I update a specific column in my gridview after a timed event?

In my web app I have a GridView that gets information from the SQL database then I have a timed event that pings the IP addresses every 5 seconds. If the response is less that 15ms the icon is displayed as a green tick. If more that 15ms the icon changes to a yellow exclamation mark, and when timed out a red error icon.
The code is working like it should(regarding the timed event), however the icon doesn't get replaced according to the timed response instead it adds a new icon every time
for example:
if the time is less that 15ms on first timed event:
Y
if the time is more than 15 ms on second timed event:
Y !
As you can see the Y remains whereas it should then just display the !
This is my code (aspx)
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:constr %>"
SelectCommand="SELECT ip, host, device FROM [servers]"></asp:SqlDataSource>
<asp:Timer runat="server" ID="UpdateTimer" Interval="5000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</triggers>
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="gridview" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="ip" Width="100%">
<AlternatingRowStyle CssClass="AltRow"></AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Image ID="Image3" runat="server" Visible="False" ImageUrl="~/Images/green.png" />
<asp:Image ID="Image4" runat="server" Visible="False" ImageUrl="~/Images/red.png" />
<asp:Image ID="Image5" runat="server" Visible="False" ImageUrl="~/Images/yellow.png" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="ip" HeaderText="IP Address" />
<asp:BoundField DataField="host" HeaderText="Host Name" />
<asp:BoundField DataField="device" HeaderText="Description" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
For the code behind:
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
Servers();
}
private void Servers()
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Image Image3 = (Image)row.FindControl("Image3");
Image Image4 = (Image)row.FindControl("Image4");
Image Image5 = (Image)row.FindControl("Image5");
TimedPanel.Update();
string destIP = GridView1.DataKeys[row.RowIndex].Value.ToString();
{
try
{
Ping p = new Ping();
PingReply reply;
reply = p.Send(destIP);
if (reply.Status == IPStatus.Success)
{
if (reply.RoundtripTime > 15)
{
Image5.Visible = true;
Image5.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
else
Image3.Visible = true;
Image3.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
else
{
Image4.Visible = true;
Image4.ToolTip = reply.Status.ToString();
}
}
catch (PingException err)
{
Image4.ToolTip = err.Message.ToString();
Image4.Visible = true;
}
}
}
}
}
What I have tried was to update the panel by using:
TimedPanel.Update();
This didn't work though. Obviously when I refresh the entire page then it works but don't want to do that. I am also not sure if one can update just the column where the icons are being displayed after each timed event.
Any suggestions on how I get the icons to display one at a time after the timed event?
Thanks
Okay, I have resolved the issue.
Remove the Images from the ItemTemplate and add a panel
<ItemTemplate>
<asp:Panel runat="server" ID="Panel4"></asp:Panel>
</ItemTemplate>
Change the code behind to
Image Image2 = new Image();
Image Image3 = new Image();
Image Image4 = new Image();
Panel serverPanel = (Panel)row.FindControl("Panel4");
Add the images like this:
if (reply.Status == IPStatus.Success)
{
if (reply.RoundtripTime > 50)
{
Image2.ImageUrl = "../Images/yellow.png";
serverPanel.Controls.Add(Image2);
Image2.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
else
{
Image3.ImageUrl = "../Images/green.png";
serverPanel.Controls.Add(Image3);
Image3.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
}
else
{
Image4.ImageUrl = "../Images/red.png";
serverPanel.Controls.Add(Image4);
Image4.ToolTip = reply.Status.ToString();
}
}
catch (PingException err)
{
Image4.ImageUrl = "../Images/red.png";
serverPanel.Controls.Add(Image4);
Image4.ToolTip = err.Message.ToString();
}
so it will then be:
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:constr %>"
SelectCommand="SELECT ip, host, device FROM [addfirewall]"></asp:SqlDataSource>
<asp:Timer runat="server" ID="UpdateTimer3" Interval="5000" OnTick="UpdateTimer3_Tick" />
<asp:UpdatePanel runat="server" ID="UpdatePanel3" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView4" CssClass="gridview" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="SqlDataSource4" DataKeyNames="ip" Width="100%">
<AlternatingRowStyle CssClass="AltRow"></AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Panel runat="server" ID="Panel4"></asp:Panel>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="ip" HeaderText="IP Address" />
<asp:BoundField DataField="host" HeaderText="Host Name" />
<asp:BoundField DataField="device" HeaderText="Description" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer3" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
Code Behind:
private void Servers()
{
foreach (GridViewRow row in GridView4.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Image Image2 = new Image();
Image Image3 = new Image();
Image Image4 = new Image();
Panel serverPanel = (Panel)row.FindControl("Panel4");
string destIP = GridView4.DataKeys[row.RowIndex].Value.ToString();
{
try
{
Ping p = new Ping();
PingReply reply;
reply = p.Send(destIP);
if (reply.Status == IPStatus.Success)
{
if (reply.RoundtripTime > 50)
{
Image2.ImageUrl = "../Images/yellow.png";
serverPanel.Controls.Add(Image2);
Image2.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
else
{
Image3.ImageUrl = "../Images/green.png";
serverPanel.Controls.Add(Image3);
Image3.ToolTip = Convert.ToString("RoundTripTime: " + reply.RoundtripTime + "ms");
}
}
else
{
Image4.ImageUrl = "../Images/red.png";
serverPanel.Controls.Add(Image4);
Image4.ToolTip = reply.Status.ToString();
}
}
catch (PingException err)
{
Image4.ImageUrl = "../Images/red.png";
serverPanel.Controls.Add(Image4);
Image4.ToolTip = err.Message.ToString();
}
}
}
}
}

How to set 3 radiobutton with its groupname in a repeater

I need to set 3 different groups of radio button in a repeater. Using groupname property for it wasn't enough. So, after researching, I use a bit of JS and it works. My problem is when I want to implement more than one group of radiobuttons. Can anyone help me?
My best approach is:
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('repeaterImages.*nombreLogo',this)";
string scriptApp = "SetUniqueRadioButton('repeaterImages.*nombreLogoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('repeaterImages.*nombreLogoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
With this code just getting 3 rows of radiobutton, sharing groupname behavior for all of them... (I want groupname behavior per row...)
Piece of cake. Prove how newie I am in JS. I am posting the solution because is a recurrent issue in asp programming and this bug is known. Beside I cant find the solution for some radio button.
JS.
<script>
function SetUniqueRadioButton(text, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if ((elm.type == 'radio') && (elm.value == text)) {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('rbLogoSeleccionado',this)";
string scriptApp = "SetUniqueRadioButton('rbLogoSeleccionadoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('rbLogoSeleccionadoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>

Adding Dynamic Rows in Gridview and How to retain selected option from user control in Gridview

I have created user control named CRE.ascx,this control has 3 dropdownlist.
First dropdownlist bind data on pageload.Second and third based on SelectedIndexChanged.
<table cellspacing="0" cellspading="0" style="width:550px;height:30px;">
<tr>
<td style="width:30%;">
<asp:DropDownList ID="ddlCRE" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlCRE_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlDataPoints" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlDataPoints_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlErrorCode" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlErrorCode_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:10%;">
<asp:TextBox ID="tbxErrorScore" runat="server" style="height:17px;border:0px;font-family:'Segoe UI';font-size:13px;font-weight:500;color:white;background-color:#333333;
width:65px;" ReadOnly="true"> </asp:TextBox>
</td>
</tr>
</table>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Get Ticket Type Values
dbtickettype = helpdsktcktusrHandler.GetTicketType("DPT0001");
ddlCRE.DataSource = dbtickettype;
ddlCRE.DataValueField = "Type_ID";
ddlCRE.DataTextField = "Type_Name";
ddlCRE.DataBind();
ddlCRE.Items.Insert(0, new ListItem("Select Type", "SLCT0000"));
}
else
{
}
}
protected void ddlCRE_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedTypeID = ddlCRE.SelectedValue.ToString();
try
{
if (selectedTypeID == "SLCT0000")
{
ddlDataPoints.Items.Clear();
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketCategory = helpdsktcktusrHandler.GetTicketCategoryDetails(selectedTypeID);
//Binding Ticket Type values to Listbox
ddlDataPoints.DataSource = dbticketCategory;
ddlDataPoints.DataValueField = "Category_ID";
ddlDataPoints.DataTextField = "Category_Name";
ddlDataPoints.DataBind();
ddlDataPoints.Items.Insert(0, new ListItem("Select Category", "SLCT0000"));
//Clear Items
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlDataPoints_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCatID = ddlDataPoints.SelectedValue.ToString();
try
{
if (selectedCatID == "SLCT0000")
{
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketSubCategory = helpdsktcktusrHandler.GetTicketSubCategoryDetails(selectedCatID);
//Binding Ticket Type values to Listbox
ddlErrorCode.DataSource = dbticketSubCategory;
ddlErrorCode.DataValueField = "Sub_Category_ID";
ddlErrorCode.DataTextField = "Sub_Category_Name";
ddlErrorCode.DataBind();
ddlErrorCode.Items.Insert(0, new ListItem("Select Subcategory", "SLCT0000"));
//Clear Items
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlErrorCode_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedSubcatID = ddlErrorCode.SelectedValue.ToString();
try
{
if (selectedSubcatID == "SLCT0000")
{
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketIssues = helpdsktcktusrHandler.GetTicketIssueDetails(selectedSubcatID);
////Binding Ticket Type values to Listbox
//ddlstIssue.DataSource = dbticketIssues;
//ddlstIssue.DataValueField = "IssueID";
//ddlstIssue.DataTextField = "Issue_Name";
//ddlstIssue.DataBind();
tbxErrorScore.Text = dbticketIssues.Rows[0][1].ToString();
}
}
catch (Exception ex)
{
}
}
then register directive and an instance of the user control added to the page.
In this main page, i have added one Gridview, user control UC1 and two buttons
included in the ItemTemplate.
<%# Register src="~/CRE.ascx" TagName="InsertNewCRE" TagPrefix="uc1" %>
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
<ContentTemplate>
<div id="dvsubCRE" class="dvsubCRE" runat="server">
<!-----[[[ GRIDVIEW ADDING CRE ]]]----->
<div id="dvAddingErrorInfo" class="dvAddingErrorInfo">
<!-- LOAD CRE DROPDOWN INFO GRID -->
<asp:GridView ID="gvCREInfo" runat="server" CssClass="gvErrorInfo" AlternatingRowStyle-CssClass="" ShowFooter="false" ShowHeader="false"
EnableViewState="True" GridLines="None" EmptyDataText="No records found" AutoGenerateColumns="true" CaptionAlign="Left" CellPadding="0"
ShowHeaderWhenEmpty="True" OnRowCreated="gvCREInfo_RowCreated" OnRowCommand="gvCREInfo_RowCommand" >
<Columns>
<asp:BoundField DataField="RowNumber" />
<asp:TemplateField ItemStyle-Width="25%" ItemStyle-Height="20px">
<ItemTemplate>
<uc1:InsertNewCRE id="UC1InserCRE" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnAddCRE" runat="server" Width="20px" Height="20px" value="" ImageUrl="~/Images/Tracker/add.png"
CommandName="ButtonAddCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton ID="imgbtnReoveCRE" runat="server" Width="20px" Height="20px" value="" Visible="false" ImageUrl="~/Images/Tracker/delete.png" CommandName="ButtonRemoveCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- LOAD CRE DROPDOWN INFO GRID CLOSE -->
</div>
<!-----[[[ GRIDVIEW ADDING CRE CLOSE ]]]----->
</div>
</ContentTemplate>
</asp:UpdatePanel>
When main page loads, user control UC1 loaded in the gridview and pull out the data from CRE.ascx page.I have bind dummy data on page load to the gridview.Add new row along with user control mentioned in the RowCommand.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
gvCREInfo.DataSource = dt;
gvCREInfo.DataBind();
}
else
{
}
}
catch (Exception ex)
{
}
}
protected void gvCREInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
#region ADD NEW CRE ROW
if (e.CommandName == "ButtonAddCRERow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvCREInfo.Rows[index];
int count = gvCREInfo.Rows.Count;
DataRow drCurrentRow = null;
UserControl UC1 = (UserControl)(row.Cells[0].FindControl("UC1InserCRE"));
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
for (int i = 0; i <= (count - 1); i++)
{
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
}
gvCREInfo.DataSource = dtCurrentTable;
gvCREInfo.DataBind();
}
#endregion
}
When i run this code working fine and i changed the first dropdownlist
it will pull data and bind to the second, like wise third one also.But when i click the add button selected data lost in the first row and second row control added not with data.How to retain existing selected data and load user control along with data it should not loss data event post back.Please help me and sort out this.
![enter image description here][1]
http://i.stack.imgur.com/wdYZv.jpg

How to remove the displayed controls in the panel after each selection from the DropDownList?

I am a new ASP.NET developer and I am struggling right now with the following issue; I have a panel control that has more than one GridView. Only one GridView will be displayed based on the selection from the DropDownList.
Let us assume that we have three GridViews and we have a DropDownList with three options; A, B and C. If I select A, the first GridView will be displayed. After that, if I select B, the second GridView will be displayed in addition to the first displayed GridView. What I want is after selecting any option from the dropdownlist, the GridView and Label control should be removed and replaced with the new result.
So how can I do that?
My ASP.NET code:
<asp:Panel ID="Panel1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Please Select</asp:ListItem>
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:GridView ID="GridView1" runat="server" Visible="true"></asp:GridView>
<br />
<asp:GridView ID="GridView2" runat="server" Visible="true"></asp:GridView>
<br />
<asp:GridView ID="GridView3" runat="server" Visible="true"></asp:GridView>
<br /><br />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</asp:Panel>
C# Code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex != null)
{
int option = DropDownList1.SelectedIndex;
var myList2 = new List<string>();
myList2.Add("Test");
myList2.Add("Test");
var myList3 = new List<string>();
switch (option)
{
case 1:
if (myList2.Count > 0)
{
GridView1.DataSource = myList2;
GridView1.DataBind();
GridView1.Visible = true;
}
else
{
lblMessage.BackColor = System.Drawing.Color.Yellow;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "No Data!";
}
break;
case 2:
if (myList3.Count > 0)
{
GridView1.Visible = false;
GridView2.DataSource = myList3;
GridView2.DataBind();
GridView2.Visible = true;
}
else
{
lblMessage.BackColor = System.Drawing.Color.Yellow;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "No Data!";
}
break;
case 3:
if (myList2.Count > 0)
{
GridView1.Visible = false;
GridView2.Visible = false;
GridView3.DataSource = myList2;
GridView3.DataBind();
GridView3.Visible = true;
}
else
{
lblMessage.BackColor = System.Drawing.Color.Yellow;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "No Data!";
}
break;
default:
break;
}
}
}
NOTE: As you see in my C# above that in each case in the switch statement, I am removing the controls of the preceding case but this is not the right way, because I need to remove whether GridView or Label controls after selecting any item from the dropdownlist. So is there any way of taking care of this.
Use MultiView control as described here:
Change page like this:
<asp:Panel ID="Panel1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Please Select</asp:ListItem>
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:MultiView ID="MainMultiview" runat="server">
<asp:View ID="View1" runat="server">
GridView 1
<asp:GridView ID="GridView1" runat="server" Visible="true"></asp:GridView>
<br />
</asp:View>
<asp:View ID="View2" runat="server">
GridView 2
<asp:GridView ID="GridView2" runat="server" Visible="true"></asp:GridView>
<br />
</asp:View>
<asp:View ID="View3" runat="server">
GridView 3
<asp:GridView ID="GridView3" runat="server" Visible="true"></asp:GridView>
<br />
</asp:View>
</asp:MultiView>
<br />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</asp:Panel>
and change code behind in C# class to like this:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex != null)
{
int option = DropDownList1.SelectedIndex;
var myList2 = new List<string>();
myList2.Add("Test");
myList2.Add("Test");
var myList3 = new List<string>();
switch (option)
{
case 1:
if (myList2.Count > 0)
{
//GridView1.DataSource = myList2;
//GridView1.DataBind();
//GridView1.Visible = true;
MainMultiview.SetActiveView(View1);
}
else
{
lblMessage.BackColor = System.Drawing.Color.Yellow;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "No Data!";
}
break;
case 2:
if (myList2.Count > 0)
{
//GridView1.Visible = false;
//GridView2.DataSource = myList3;
//GridView2.DataBind();
//GridView2.Visible = true;
MainMultiview.SetActiveView(View2);
}
else
{
lblMessage.BackColor = System.Drawing.Color.Yellow;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "No Data!";
}
break;
case 3:
if (myList2.Count > 0)
{
//GridView1.Visible = false;
//GridView2.Visible = false;
//GridView3.DataSource = myList2;
//GridView3.DataBind();
//GridView3.Visible = true;
MainMultiview.SetActiveView(View3);
}
else
{
lblMessage.BackColor = System.Drawing.Color.Yellow;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "No Data!";
}
break;
default:
break;
}
}
}
Notice gridview can not bind to list of string. But multiview works greate.

Hide/show table in gridview on button click event

I have project on recruitment.In this project, at one form I have a grid view which contains details of all vacancies. Along with this there is button. When user clicks on this button, available interview schedule for that particular vacancy will be visible in another grid below that row. What I did is I have placed grid view inside table and table is initially invisible. When user clicks on the image button, at that time I tried to find table from the grid view but it can not be found.
Here is the code of my .aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<table class="formtTbl" width="100%">
<tr>
<td width="10%">
</td>
<td>
</td>
<td width="10%">
</td>
</tr>
<tr>
<td>
</td>
<td align="center" class="tdtitle">
Open vacancies
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:ImageButton ID="addVacancyBtn" runat="server"
ImageUrl="~/Resources/add.png" onclick="addVacancyBtn_Click" />
Add New Vacancy</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:GridView ID="VacancyGrid" runat="server" CssClass="mGrid"
AutoGenerateColumns="False" onrowcommand="VacancyGrid_RowCommand">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ScheduleBtn" runat="server"
ImageUrl="~/Resources/01.gif"
ToolTip="View Interview Schedule" Width="20px"
CommandName="View Schedule" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="VacId" DataField="VacId" />
<asp:BoundField HeaderText="Title" DataField="VacTitle" />
<asp:BoundField HeaderText="Open" DataField="TotalOpening" />
<asp:BoundField HeaderText="Criteria" DataField="criteria" />
<asp:BoundField HeaderText="Key Skills" DataField="KeySkills" />
<asp:BoundField HeaderText="Exp" DataField="RequiredExperience" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="editBtn" runat="server"
ImageUrl="~/Resources/art-knife.png" Width="20px"
CommandName="Edit" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"/>
</ItemTemplate>
<EditItemTemplate>
Edit
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="statusLbl" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<table id="ScheduleTable" visible="false">
<tr id="abc" visible="false">
<td colspan="10">
<asp:GridView ID="scheduleGrid" runat="server" Visible="False"
AutoGenerateColumns="False" onrowcommand="scheduleGrid_RowCommand">
<Columns>
<asp:BoundField DataField="VacId" HeaderText="ID" />
<asp:BoundField DataField="VacTitle" HeaderText="Title" />
<asp:BoundField DataField="InterviewTime" HeaderText="Interview Date & Time" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="viewIntervieweesBtn" runat="server"
ImageUrl="~/Resources/document.png" ToolTip="View interiviewees" Width="20px"
CommandName="View Interviewees" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="ScheduleNotifyLbl" runat="server" Visible="false"></asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="pgr" />
</asp:GridView>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td align="left">
<asp:Label ID="notificationLbl" runat="server" Font-Size="X-Large"
ForeColor="Red" Text="Label" Visible="False"></asp:Label>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</asp:Content>
//Here is the code for my .aspx.cs page
public partial class Department_VacancyList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable VacancyTable = null;
try
{
if (!IsPostBack)
{
if (Request.QueryString["status"] != null)
{
// strStatus = Request.QueryString["status"];
Session.Add("strStatus", Request.QueryString["status"]);
}
if (Session["OpResult"] != null)
{
notificationLbl.Visible = true;
if (Session["OpResult"].ToString() == "InsertSuceess")
notificationLbl.Text = "New Vacancy Has Been Created Successfully";
if (Session["OpResult"].ToString() == "InsertFail")
notificationLbl.Text = "An Error Occured While Creating New Vacancy..";
if (Session["OpResult"].ToString() == "EditSuccess")
notificationLbl.Text = "Your Changes Has Been Saved Successfully";
if (Session["OpResult"].ToString() == "EditFail")
notificationLbl.Text = "An Error Occured While Saving Changes...";
}
using (VacancyMasterClass VacMaster = new VacancyMasterClass())
{
if (Session["strStatus"].ToString() == "1")//All Vacancies
VacancyTable = VacMaster.getTable("and DeptId=1 and CompId=1");//Change Here.
else if (Session["strStatus"].ToString() == "2")//Open Vacancies
VacancyTable = VacMaster.getTable("and DeptId=1 and CompId=1 and Status=0");//Change Here.
else if (Session["strStatus"].ToString() == "3")//Closed Vacancies
VacancyTable = VacMaster.getTable("and DeptId=1 and CompId=1 and Status=1");//Change Here.
VacancyGrid.DataSource = VacancyTable;
VacancyGrid.DataBind();
VacancyGrid.ControlStyle.Width = 650;
VacancyGrid.Columns[0].ItemStyle.Width = 20;
VacancyGrid.Columns[1].ItemStyle.Width = 10;
VacancyGrid.Columns[2].ItemStyle.Width = 150;
VacancyGrid.Columns[3].ItemStyle.Width = 20;
VacancyGrid.Columns[4].ItemStyle.Width = 190;
VacancyGrid.Columns[5].ItemStyle.Width = 190;
VacancyGrid.Columns[6].ItemStyle.Width = 20;
VacancyGrid.Columns[7].ItemStyle.Width = 30;
VacancyGrid.Columns[8].ItemStyle.Width = 30;
VacancyGrid.Columns[9].ItemStyle.Width = 0;
VacancyGrid.Columns[1].Visible = false;
if (Session["strStatus"].ToString() == "1" || Session["strStatus"].ToString() == "3")
{
VacancyGrid.Columns[7].Visible = false;
VacancyGrid.Columns[0].Visible = false;
for (int intRowcount = 0; intRowcount < VacancyTable.Rows.Count; intRowcount++)
{
Label StatusLbl = (Label)VacancyGrid.Rows[intRowcount].Cells[6].FindControl("statusLbl");
if (VacancyTable.Rows[intRowcount]["Status"].ToString() == "False")
{
StatusLbl.ForeColor = Color.Green;
StatusLbl.Text = "Open";
}
else
{
StatusLbl.ForeColor = Color.Red;
StatusLbl.Text = "Closed";
}
}
}
else if (Session["strStatus"].ToString() == "2")
VacancyGrid.Columns[8].Visible = false;
}
}
}
catch (Exception ex)
{
CommonProcedures.WriteErrorLog("Department_VacancyList", "Page_Load", ex.Message);
}
finally
{
Session.Remove("OpResult");
}
}
//protected void VacancyGrid_RowEditing(object sender, GridViewEditEventArgs e)
//{
// int intOpMode = 2;//Edit Mode
// int intVacId = Convert.ToInt32(VacancyGrid.Rows[e.NewEditIndex].Cells[1].Text);
// Response.Redirect("create_vacancyfrm.aspx?VacId="+intVacId+"&OpMode="+intOpMode);
//}
protected void addVacancyBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
int intOpMode = 1;//Edit Mode
int intVacId = 0;
Response.Redirect("create_vacancyfrm.aspx?DeptId=1&CompId=1&VacId=" + intVacId + "&OpMode=" + intOpMode);//Change Here
}
protected void VacancyGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable InterviewScheduleTable = null;
int intVacid = 0;
try
{
if (e.CommandName == "View Schedule")
{
int intRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow Row = VacancyGrid.Rows[intRowIndex];
//Table ScheduleTable = (Table)Row.FindControl("ScheduleTable");
intVacid = Convert.ToInt32(Row.Cells[1].Text);
GridView scheduleGrid = (GridView)Row.FindControl("scheduleGrid");
Label ScheduleNotifyLbl = (Label)Row.FindControl("ScheduleNotifyLbl");
if (scheduleGrid.Visible == false)
{
using (vwVacInterviewShcedule oInterviewSchedule = new vwVacInterviewShcedule())
{
InterviewScheduleTable = oInterviewSchedule.getTable("and VacId=" + intVacid);
if (InterviewScheduleTable.Rows.Count > 0)
{
scheduleGrid.Visible = true;
scheduleGrid.DataSource = InterviewScheduleTable;
scheduleGrid.DataBind();
scheduleGrid.ControlStyle.Width = 650;
scheduleGrid.Columns[0].ItemStyle.Width = 10;
scheduleGrid.Columns[1].ItemStyle.Width = 300;
scheduleGrid.Columns[2].ItemStyle.Width = 250;
scheduleGrid.Columns[3].ItemStyle.Width = 90;
}
else
{
if (ScheduleNotifyLbl.Visible == false)
{
ScheduleNotifyLbl.Visible = true;
ScheduleNotifyLbl.Text = "Interview is yet to schedyule for this vacancy";
}
else
{
ScheduleNotifyLbl.Visible = false;
}
}
}
}
else
{
scheduleGrid.Visible = false;
}
}
ViewState.Add("VacId", intVacid);
if (e.CommandName == "Edit")
{
int intOpMode = 2;
int intRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow Row = VacancyGrid.Rows[intRowIndex];
int intVacId = Convert.ToInt32(Row.Cells[1].Text);
Response.Redirect("create_vacancyfrm.aspx?VacId=" + intVacId + "&OpMode=" + intOpMode);
}
}
catch (Exception ex)
{
CommonProcedures.WriteErrorLog("Department_VacancyList", "VacancyGrid_RowCommand", ex.Message);
}
finally
{
InterviewScheduleTable = null;
}
}
protected void scheduleGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
foreach (GridViewRow Row in VacancyGrid.Rows)
{
GridView ScheduleGrid = (GridView)Row.FindControl("scheduleGrid");
if (e.CommandName == "View Interviewees")
{
int intRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow ScheduleGridRow = ScheduleGrid.Rows[intRowIndex];
int intVacId = Convert.ToInt32(ScheduleGridRow.Cells[3].Text);
Session.Add("Time",ScheduleGridRow.Cells[2].Text);
Response.Redirect("~/Department Head/Schedulefrm.aspx?VacId="+intVacId);
}
}
}
catch (Exception ex)
{
CommonProcedures.WriteErrorLog("Department_VacancyList", "scheduleGrid_RowCommand", ex.Message);
}
}
}
Please show me my problem...
You have provided too much code, that can't be read easily. You have to narrow it down to a specific point.
Let me try to help you on your specific problem.
If you set the control visible=false it will not render at client side and you can't make that control visible later on in client side. Have a look at this similar thread to get an idea how to proceed: Want to make the visibility true from client side of the control which made invisible from server side

Categories

Resources