call javascript window.onload after SelectedIndexChanged event fire - c#

//my problem is when i fire SelectedIndexChanged event of ddlmodalitylist asynchronously(ajax call) then javascript load event is not fired..thats y i have to fire onload event from server side.
window.onload = body_Onload;
function body_Onload() {
//javascript code
}
protected void ddlModalityList_SelectedIndexChanged(object sender, EventArgs e)
{
ddlStudy.Items.Clear();
ListItem selectedPair = ddlModalityList.SelectedItem;
string str= selectedPair.Value;
int ID= Convert.ToInt32(str);
if (ID == -1)
{
// ddlStudy.Items.Clear();
return;
}
DataTable dataTableStudy = null;
dataTableStudy = objSqlDbComm.ExecuteDatasetQuery(strSQL).Tables[0];
var dictioneryStudy = new Dictionary<int, string>();
foreach (DataRow dr in dataTableStudy.Rows)
{
dictioneryStudy.Add(Convert.ToInt32(dr["Study_ID"]), dr["Study_Desc"].ToString());
}
ddlStudy.DataTextField = "Value";
ddlStudy.DataValueField = "Key";
ddlStudy.DataSource = dictioneryStudy;
ddlStudy.DataBind();
ddlStudy.Items.Insert(0, new ListItem("[Select]", "-1"));
ddlStudy.Items[0].Selected = true;
}

Sys.Application.add_init(your_bodyload_function);

Related

Dynamically added dropdownlist losing value on postback

Hi i am creating dropdownlist dynamically but on post back it is loosing the value and i am unable to get values on button click event.
private void CreateDropdownListEmployee(string id,Panel pnl, DataTable dt)
{
DropDownList drp = new DropDownList();
drp.ID = id;
drp.CssClass = "activeuserTxt";
drp.ClientIDMode = ClientIDMode.Static;
drp.DataSource = dt;
drp.DataTextField = "name";
drp.DataValueField = "id";
drp.DataBind();
pnl.Controls.Add(drp);
}
For the dynamic texbox i am using the below code on PAge_Init
protected void Page_Init(object sender, EventArgs e)
{
try
{
int SNID = 0;
List<string> keysNetmr = Request.Form.AllKeys.Where(key => key.Contains("txt")).ToList();
foreach (string key in keysNetmr)
{
this.CreateTextBox("txtNermr" + SNID, 100, pnlSN);
SNID++;
}
}
catch (Exception ex) { }
}
private void CreateTextBox(string id, int width, Panel pnl)
{
TextBox txt = new TextBox();
txt.ID = id;
txt.Width = width;
txt.Attributes.Add("autocomplete", "off");
txt.CssClass = "activeuserTxt";
pnl.Controls.Add(txt);
}
Can anyone help me on this.

'Find and Save' functionality not working

First time poster, long time lurker. I am having some trouble with my ASP.NET page, and I hope someone can help me resolve my issue.
Basically, I have a bunch of checkboxes in a gridview, and two buttons: a 'find' button, and a 'save' button. The 'find' can set the value of the checkbox, but if a user unchecks it, I want to capture that change when the user hits 'save'. Currently, it does not work.
Relevant ASPX:
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeBehind="FindTransactions.aspx.cs" Inherits="Basic.FindTransactions" MasterPageFile="~/Trans.Master" %>
Relevant Code Behind here:
Page:
public partial class FindTransactions : System.Web.UI.Page
{
GridView _gridview = new GridView() { ID = "_gridView" };
DataTable _datatable = new DataTable();
Int32 _buyerID = new Int32();
protected void Page_Load(object sender, EventArgs e)
{
}
"Find" button:
protected void Find_Click(object sender, EventArgs e)
{
//truncated
_datatable.Rows.Add(
//filled with other data from a custom object.
);
ViewState["_datatable"] = _datatable;
ViewState["_buyerID"] = _buyerID;
BuildGridView((DataTable)ViewState["_datatable"],(Int32)ViewState["buyerID"]);
}
BuildGridView function:
protected void BuildGridView(DataTable d, Int32 b)
{
_gridview.DataKeyNames = new String[] {"Transaction ID"};
_gridview.AutoGenerateColumns = false;
_gridview.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
for(Int32 i = 0; i < d.Columns.Count; i++)
{
Boundfield boundfield = new BoundField();
boundfield.DataField = d.Columns[i].ColumnName.ToString();
boundfield.HeaderText = d.Columns[i].ColumnName.ToString();
_gridview.Columns.Add(boundfield);
}
_gridview.DataSource = d;
_gridview.DataBind();
//truncated
Panel1.Controls.Add(_gridview);
}
Row Bound Event handler:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String controlID = "checkBox";
CheckBox c = new CheckBox() { ID = controlID};
c.Enabled = true;
Boolean success;
Boolean v;
success = Boolean.TryParse(e.Row.Cells[8].Text, out v);
e.Row.Cells[8].Controls.Add(c);
if (success)
{
c.Checked = v;
if (c.Checked)
{
//Will uncomment once other things work
//e.Row.Visible = false;
}
}
else
{
c.Checked = false;
}
}
}
All of that works. Here is where it starts to break down:
"Save" button:
protected void Save_Click(object sender, EventArgs e)
{
//Both for troubleshooting and both return 0. (Expected for datatable)
Label1.Text = _gridview.Rows.Count.ToString();
Label2.Text = _datatable.Rows.Count.ToString();
/*truncated
*/
if (grid.Rows.Count == 0)
{
BuildGridView((DataTable)ViewState["infoTable"], (Int32)ViewState["guestID"]);
}
foreach (GridViewRow r in grid.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)r.FindControl("checkBox");
if (cb != null && cb.Checked)
{
//This never seems to modify the label.
//Will put code to modify database here.
Label2.Text += "Hi " + r.RowIndex.ToString();
}
}
}
}
After I hit the save button, PostBack occurs and GridView is empty (Rows.Count is 0). ViewState appears to be lost before I get a chance to loop through the GridView rows to determine the checkbox values.
At the end of it all, I just want to capture the status of those checkboxes, changed by user interaction or not, by hitting the 'Save' button.
I found some other articles, but a lot of them haven't worked when I tried implementing the various fixes.
This one seems to be the closest that describes my issue, and the code is structured similarly, but I don't quite understand how to implement the fix: GridView doesn't remember state between postbacks
[New simplified code to illustrate problem:]
namespace GridViewIssue
{
public partial class GridViewNoMaster : System.Web.UI.Page
{
GridView _gridView = new GridView() { ID = "_gridView" };
DataTable _dataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Find_Click(object sender, EventArgs e)
{
BuildDataTable();
List<String> list = new List<String>();
list.Add("1");
list.Add("User");
list.Add("10/12/2014");
foreach (String s in list)
{
_dataTable.Rows.Add(
list[0],
list[1],
list[2]
);
}
BuildGridView();
//Feedback.Text = _gridView.Rows.Count.ToString();
}
protected void Save_Click(object sender, EventArgs e)
{
Feedback.Text = "Save Clicked, PostBack: " + IsPostBack + ", GridView Row Count: " + _gridView.Rows.Count + ", GridView ViewState: " + _gridView.EnableViewState;
foreach (GridViewRow r in _gridView.Rows)
{
if(r.RowType == DataControlRowType.DataRow)
{
Feedback.Text = "In DataRow type" + _gridView.Rows.Count;
}
}
}
protected void BuildDataTable()
{
_dataTable.Columns.Add("Transaction ID", typeof(String));
_dataTable.Columns.Add("Name", typeof(String));
_dataTable.Columns.Add("Date", typeof(String));
}
protected void BuildGridView()
{
for (Int32 i = 0; i < _dataTable.Columns.Count; i++)
{
BoundField b = new BoundField();
b.DataField = _dataTable.Columns[i].ColumnName.ToString();
b.HeaderText = _dataTable.Columns[i].ColumnName.ToString();
_gridView.Columns.Add(b);
}
_gridView.DataKeyNames = new String[] { "Transaction ID" };
_gridView.AutoGenerateColumns = false;
_gridView.DataSource = _dataTable;
_gridView.DataBind();
Panel1.Controls.Add(_gridView);
}
}
}

Not able to call a javascript function through alert

I am creating an alert and trying to call a click event through javascript function when "OK" of alert is pressed.It runs pretty well if I create the alert on rpage_Load but When I crate the alert on clicking of a buttton, then on pressing "OK" of alert the required click event is not called.
This is how I create the alert
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Startup", "Test();", true);
}
This is the javascript function which calls a click event
<script type="text/javascript">
function Test() {
alert('There is no Bookmarked Question Available');
document.getElementById('btnReview').click();
}
</script>
This is the click event which will be called through Test()
protected void btnReview_Click(object sender, EventArgs e)
{
count = int.Parse((string)ViewState["S.NO"]);
dt1 = (DataTable)ViewState["Question"];
if (rbOption.SelectedValue != "")
{
string strUserOpt = rbOption.SelectedItem.Text;
strUserOpt = strUserOpt.Substring(20);
dt1.Rows[count - 1][9] = strUserOpt;
dt1.Rows[count - 1][10] = rbOption.SelectedValue;
}
lblReview.Visible = true;
tblQues.Visible = false;
tblReview.Visible = true;
btnBookMark.Text = "Bookmark";
btnBookMark.Font.Bold = false;
btnBookMark.BackColor = Color.Empty;
lblQuestionNo.Visible = false;
lblTopic.Visible = false;
lblTestHead.Visible = false;
DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Status");
dt.Columns.Add("BookMarked");
DataRow dr1;
foreach (DataRow dr in dt1.Rows)
{
dr1 = dt.NewRow();
dr1[0] = dr[0].ToString() ;
if (dr[9].ToString() != "") { dr1[1] = "Attempted"; } else { dr1[1] = "Un-attempted"; }
if (dr[11].ToString() != "") { dr1[2] = "Yes"; } else { dr1[2] = "No"; }
dt.Rows.Add(dr1);
}
dt.AcceptChanges();
ClsDataBind.DoGridViewBind(grdReview, dt, _errMsg);
btnBookMark.Visible = false;
btnNext.Visible = false;
btnPrevious.Visible = false;
btnReview.Visible = false;
}
The main problem may be you are clicking Button1 after btnReview because under btnReview_Click
this happens
btnReview.Visible = false;
This means you will not be able to use Button1_Click event unless
btnReview.Visible = true;

List box pops back to the first item after SelectedIndexChange event fires

I have a 3 dropdownlist control with a selectedindexchanged event that fires correctly. However, when you select an item from the list the index value that is returned to the selectedindexchanged event does not change; the list box pops back to the first item in the list. Any help would be appreciated. ~Dharmendra~
`public partial class Production : System.Web.UI.Page
{
EmployeeQuotientCL.Production _production = null;
DataSet dsNatureOfWork = new DataSet();
DataSet dsProjectRegion = new DataSet();
DataSet dsCountyDetails = new DataSet();
DataSet dsWorkType = new DataSet();
DataSet dsTask = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userEcode=Convert.ToString(Session["UserID"]);
_production = new EmployeeQuotientCL.Production();
dsNatureOfWork = _production.GetNatureOfWork();
if (dsNatureOfWork.Tables[0].Rows.Count > 0)
{
BindDdlNatureOfWork(dsNatureOfWork);
}
else
{
}
}
}
public void BindDdlNatureOfWork(DataSet dsNatureOfWork)
{
ddlNatureofWork.DataSource = dsNatureOfWork.Tables[0];
ddlNatureofWork.DataTextField = "NatureOfWorkName";
ddlNatureofWork.DataValueField = "NatureOfWorkID";
ddlNatureofWork.DataBind();
ddlNatureofWork.Items.Insert(0, "--Select Nature of Work--");
}
public void FillRegionProject(int NatureOfWorkID)
{
if ((NatureOfWorkID != null) || (NatureOfWorkID != 0))
{
_production = new EmployeeQuotientCL.Production();
dsProjectRegion = _production.GetProjectRegion(NatureOfWorkID);
if (dsProjectRegion.Tables[0].Rows.Count > 0)
{
ddlRegionProjectName.DataSource = dsProjectRegion.Tables[0];
ddlRegionProjectName.DataTextField = "RegionProjectName";
ddlRegionProjectName.DataValueField = "RegionProjectID";
ddlRegionProjectName.DataBind();
ddlRegionProjectName.Items.Insert(0, "--Select Region/Project--");
}
else
{
}
}
}
protected void ddlRegionProjectName_SelectedIndexChanged(object sender, EventArgs e)
{
int RegionProjectID = Convert.ToInt32(ddlRegionProjectName.SelectedValue.ToString());
FillCounty(RegionProjectID);
ddlRegionProjectName.SelectedIndex = 0;
}
public void FillCounty(int regionprojectID)
{
if ((regionprojectID != null) || (regionprojectID != 0))
{
_production = new EmployeeQuotientCL.Production();
dsCountyDetails = _production.GetCounty(regionprojectID);
if (dsCountyDetails.Tables[0].Rows.Count > 0)
{
ddlCountyName.DataSource = dsCountyDetails.Tables[0];
ddlCountyName.DataTextField = "CountyName";
ddlCountyName.DataValueField = "CountyID";
ddlCountyName.DataBind();
ddlCountyName.Items.Insert(0, "--Select County--");
}
else
{
}
}
}
protected void ddlNatureofWork_SelectedIndexChanged(object sender, EventArgs e)
{
int NowID = Convert.ToInt32(ddlNatureofWork.SelectedValue.ToString());
FillRegionProject(NowID);
ddlRegionProjectName.SelectedIndex = 0;
}
}
}`
You are doing ddlRegionProjectName.SelectedIndex = 0; in every SelectedIndexChanged event.
You have no event for ddlCountyName control in the code shared by you.

RowCommand not getting fired on Dynamically created GridView

I am creating a gridview dynamically with a ButtonField and several BoundFields. ButtonField button type is LinkButton. If i run it the buttonclick triggers a post back but rowCommand is not triggered. It is not triggered even if i use AutogenerateSelectButton. The event is dyanamically bound. Code As follows:
protected void B_Search_Click(object sender, EventArgs e) //Search buttonclick that creates and displays the gridview
{
gd = getGridView(); //defines the gridview with columns and buttonfield
gd.DataSource = executeAdvanceSearch(); //retrieves data from DB as Dataset
gd.DataBind();
gd.RowCommand += new GridViewCommandEventHandler(gdView_RowCommand); //Rowcommand event binding
PlaceHolder1.Controls.Add(gd);
}
protected void gdView_RowCommand(object sender, GridViewCommandEventArgs e) //not getting triggered on postback
{
int index = Convert.ToInt32(e.CommandArgument);
GridView gdView = (GridView)sender;
if (e.CommandName == "IDClick")
{
//Do something
}
}
private GridView getGridView()
{
GridView gdView = new GridView();
gdView.AutoGenerateColumns = false;
gdView.AutoGenerateSelectButton = true;
string name;
string[] field = ZGP.BLL.Search.getResultFormat(Convert.ToInt32(DDL_ResultView.SelectedValue), out name); //Ignore. This jst gets columnNames
if (field.Count() != 0)
{
gdView.Columns.Add(getSelectButton()); //Adds linkbutton
foreach (string cName in field) //ignore. This adds columns.
if (!String.IsNullOrEmpty(cName))
{
gdView.Columns.Add(GV_DataColumn.getGridViewColumn((DataColumnName)Enum.Parse(typeof(DataColumnName), cName))); //Ignore. adds columns
}
}
return gdView;
}
private ButtonField getSelectButton()
{
ButtonField _bf = new ButtonField();
_bf.ButtonType = ButtonType.Link;
_bf.HeaderText = "ID";
_bf.DataTextField = "ID";
_bf.CommandName = "IDClick";
return _bf;
}
Thanks for the help.
if (e.CommandName=="CommandName")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
string boundFieldText= row.Cells[0].Text;
}
You'll need to create the grid view on each postback.

Categories