ASP.Net gridview not refreshing when used with Ajaxtoolkit Upload control - c#

I have an asp.net web page that allows for manual entry of a record, or an import from an excel spreadsheet to import multiple records.
After the records are added by either process, they display in a Gridview control (bound to a SQLDataReader). This allows the user to edit or delete a record before submitting the entire dataset for processing.
I'm using an Ajax Toolkit AsyncFileUpload control to handle the import. The UploadedComplete c# function runs properly and the records are inserted into the SQL table. The code then calls my DataBindGrid() function to refresh the grid. I can step through the code and see that every line is executing, however, it seems like it never actually finishes, even though stepping through debugging completes.
Two steps are not actually completing, the grid refresh and the label display that indicates to the user that the process is complete.
For testing purposes, I've added a linkButton that calls the BindDataGrid() when clicked. This works to refresh the grid and to also display the status label. It's not a permanent solution, it would be too risky to have a user remember to refresh, they are likely to think that all their records have already been submitted.
At first I thought my problem was trying to do more inside the UploadComplete function then just upload the file (I'm reading the Excel file that was uploaded), so I broke out the code and added a button for the user to click to initiate the actual data processing. This failed because although I could see the file name being saved into a hidden form during the UploadComplete function, when I went to read that hidden field, the data was no longer in it. I'm not loosing the values in any of the other hidden fields.
I've been researching this for 3 days and I'm really stuck. I'm assuming that I am having a problem with postback, but have no clue at this point.
Here is my code:
<%# Page Title="" Language="C#" MasterPageFile="~/WTIMS.Master" AutoEventWireup="true" CodeBehind="OptionsEntry.aspx.cs" Inherits="WTIMS_OptionsEntry.Pages.OptionsEntry" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" language=javascript>
function uploadError(sender, args) {
var errMsg = args.get_errorMessage();
updateUploadStatus("error", errMsg);
}
function updateUploadStatus(status, message) {
var uploadStatLabel = document.getElementById('ContentPlaceHolder1_lblError');
uploadStatLabel.innerText = message;
if (status == "error") {
uploadStatLabel.className = "LabelErrorMessage";
}
else {
uploadStatLabel.className = "LabelScucessMessage";
}
}
function startUpload(sender, args) {
var fileName = args.get_fileName();
var fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
if (fileExt == "xlsx") {
return true;
}
else {
var err = new Error()
err.name = "Upload Error";
err.message = "Only .xlsx files can be uploaded";
throw (err);
return false;
}
}
function uploadComplete(sender, args) {
var rowCount = sender.rowCount;
}
</script>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<table width = 100% cellpadding=1>
<tr>
<td colspan=2>
<asp:Label ID="Label19" runat="server" Text="Upload batch" CssClass=LabelInfo></asp:Label>
</td>
</tr>
<tr>
<td width=50%>
<asp:AsyncFileUpload
ID="AsyncFileUpload1"
Width=400px
ThrobberID=Throbber
UploaderStyle=Modern
CompleteBackColor = "#9BCD9B"
ErrorBackColor="#D44942"
OnClientUploadStarted="startUpload"
OnClientUploadError="uploadError"
OnClientUploadComplete="uploadComplete"
OnUploadedComplete=AsyncFileUpload1_UploadedComplete
OnUploadedFileError=AsyncFileUpload1_UploadedFileError
UploadingBackColor=AliceBlue
runat="server" />
<asp:Label ID="Throbber" runat="server" Text="Label" Style="display:none">
<img src="../../images/LoadingWait.gif" alt="loading" />
</asp:Label>
</td>
</tr>
<tr>
<td>
<asp:LinkButton ID="lkbRefresh" CssClass=linkButton
Text = "Records Upload, Click to View" runat="server"
onclick="lkbRefresh_Click">LinkButton</asp:LinkButton>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblError" runat="server" Text="" CssClass="LabelErrorMessage"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblStatus" runat="server" Text="" CssClass=LabelFormLabel></asp:Label>
</td>
</tr>
</table>
asp.net code for Grid:
<table>
<tr>
<td>
<asp:Label ID="Label18" runat="server" Text="Pending Options" CssClass=LabelInfo></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit Pending Options"
CssClass=button onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grdOptions"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="OptionRecordID"
EmptyDataText="You Have no pending Options"
onrowdatabound="grdOptions_RowDataBound">
<FooterStyle CssClass="FooterStyle" />
<HeaderStyle CssClass="HeaderStyle" />
<RowStyle CssClass="RowStyle" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<PagerStyle CssClass="PagerStyle" />
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:LinkButton ID="lkbSave" runat="server" Text= "Save" CssClass=linkButton onclick="lkbSave_Click"></asp:LinkButton>
<asp:LinkButton ID="lkbCancek" runat="server" Text="Cancel" CssClass=linkButton onclick="lkbCancel_Click"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="lkbEdit" runat="server" Text= "Edit" CssClass=linkButton onclick="lkbEdit_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OptionRecordID" InsertVisible="False"
SortExpression="OptionRecordID" Visible="False">
<EditItemTemplate>
<asp:Label ID="lblOptionIDEdit" runat="server" Text='<%# Eval("OptionRecordID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblOptionID" runat="server" Text='<%# Bind("OptionRecordID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SecurityID" SortExpression="SecurityID">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("SecurityID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Symbol" SortExpression="Symbol">
<EditItemTemplate>
<asp:TextBox ID="txtSymbolEdit" Width=75px runat="server" Text='<%# Bind("Symbol") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Symbol") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Call/Put" SortExpression="CallPut">
<EditItemTemplate>
<asp:DropDownList ID="ddlPutCallEdit" runat="server" CssClass=dropdownList SelectedValue='<%# Bind("CallPut") %>'>
<asp:ListItem Text="Select" Value="Select"></asp:ListItem>
<asp:ListItem Text ="Put" Value = "Put"></asp:ListItem>
<asp:ListItem Text ="Call" Value = "Call"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("CallPut") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Buy Write" SortExpression="BuyWrite">
<EditItemTemplate>
<asp:DropDownList ID="ddlWtriteBuyEdit" runat="server" CssClass=dropdownList SelectedValue='<%# Bind("BuyWrite") %>'>
<asp:ListItem Text="Select" Value="Select"></asp:ListItem>
<asp:ListItem Text ="Buy" Value = "Buy"></asp:ListItem>
<asp:ListItem Text ="Write" Value = "Write"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label8" runat="server" Text='<%# Bind("BuyWrite") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="Price">
<EditItemTemplate>
<asp:TextBox ID="txtPriceEdit" Width=75px runat="server" Text='<%# Bind("Price") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Price") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiration Date" SortExpression="ExpirationDate">
<EditItemTemplate>
<asp:TextBox ID="txtExpirationDateEdit" Width=100px runat="server" Text='<%# Convert.ToDateTime(Eval("ExpirationDate")).ToString("d") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Convert.ToDateTime(Eval("ExpirationDate")).ToString("d") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescriptionEdit" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UploadStatus" SortExpression="UploadStatus">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<%# Bind("UploadStatus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lkbDelete" runat="server" CssClass=linkButton Text="Delete" onclick="lkbDelete_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
C# Code:
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
strFileName = Server.MapPath("~/Files/" + this.hdnSessionID.Value + "_uploaded.xlsx");
string strUploadFileName = AsyncFileUpload1.FileName.ToString();
InsertData.InsertLogMessage("File to upload: " + strFileName, "OptionsEntry", this.hdnUserID.Value);
this.hdnUploadFileName.Value = strFileName;
AsyncFileUpload1.SaveAs(strFileName);
InsertData.InsertLogMessage("File saved: " + strFileName, "OptionsEntry", this.hdnUserID.Value);
UploadData(strFileName);
DataBindGrid();
}
protected void UploadData(string strUploadFileName)
{ //process the file that was uploaded
try
{
InsertData.InsertLogMessage("Starting Upload", "OptionsEntry", this.hdnUserID.Value);
int i = 0;
// string strFileName = this.hdnUploadFileName.Value;
FileStream myStream = File.Open(strUploadFileName, FileMode.Open, FileAccess.Read);
IExcelDataReader myReader = ExcelReaderFactory.CreateOpenXmlReader(myStream);
myReader.IsFirstRowAsColumnNames = true;
DataSet result = myReader.AsDataSet();
foreach (DataTable dt in result.Tables)
{
foreach (DataRow dr in dt.Rows)
{
Boolean blnIsValid = true;
//code here to loop through file and insert records
InsertData.InsertOptionEntryFormData(strSymbol, strCallPut, strUnformattedPrice, dtmExpirationDate, strDescription, strBuyWrite, this.hdnUserID.Value, strTicker, strStatus);
i = i + 1;
}
}
this.lblStatus.Text = i + " records have been imported to the pending table. Please review and correct any errors before submitting.";
InsertData.InsertLogMessage( i + " records have been imported", "OptionsEntry", this.hdnUserID.Value);
DataBindGrid();
}
catch (Exception ex)
{
InsertData.InsertLogMessage("An error occured: " + ex.Message, "OptionsEntry", this.hdnUserID.Value);
this.lblStatus.Text = "There was a problem importing the data, please check the file and try again.";
}
}
protected void DataBindGrid()
{
this.grdOptions.DataSource = GetData.GetOptionEntryFormData(this.hdnUserID.Value);
this.grdOptions.DataBind();
}
Any suggestions would be greatly appreciated!
Christine
EDIT - Code for the grdOptions
protected void grdOptions_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblStatus = (Label)e.Row.Cells[9].Controls[1];
if (lblStatus.Text == "Invalid")
{
e.Row.CssClass = "RowError";
}
else
{
if (e.Row.RowState == DataControlRowState.Alternate)
{
e.Row.CssClass = "AlternatingRowStyle";
}
else
{
e.Row.CssClass = "RowStyle";
}
}
}
}
#region Grid Link Actions
protected void lkbSave_Click(object sender, EventArgs e)
{
this.lblErrorMessage.Visible = false;
ClearFormColor();
Boolean blnIsValid = true; //start off assuming everthing is valid
//get the row that we are sitting on
WebControl wc = (WebControl)sender;
GridViewRow row = (GridViewRow)wc.NamingContainer;
//get the data we need
Label lblOptionIDEdit = (Label)row.FindControl("lblOptionIDEdit");
int intOptionIDEdit = int.Parse(lblOptionIDEdit.Text);
TextBox txtSymbolEdit = (TextBox)row.FindControl("txtSymbolEdit");
strSymbol = txtSymbolEdit.Text;
if(!ValidateSymbol())
{
ToggleTextBoxColor(false,txtSymbolEdit);
blnIsValid = false;
}
DropDownList ddlPutCallEdit = (DropDownList)row.FindControl("ddlPutCallEdit");
strCallPut = ddlPutCallEdit.SelectedValue;
if(!ValidateCallPut())
{
ToggleDropDownColor(false,ddlPutCallEdit);
blnIsValid = false;
}
DropDownList ddlWtriteBuyEdit = (DropDownList)row.FindControl("ddlWtriteBuyEdit");
strBuyWrite = ddlWtriteBuyEdit.SelectedValue;
if(!ValidateBuyWrite())
{
ToggleDropDownColor(false,ddlWtriteBuyEdit);
blnIsValid= false;
}
TextBox txtPriceEdit = (TextBox)row.FindControl("txtPriceEdit");
strPrice = txtPriceEdit.Text;
if(!ValidateStrikePrice())
{
ToggleTextBoxColor(false,txtPriceEdit);
blnIsValid= false;
}
TextBox txtExpirationDateEdit = (TextBox)row.FindControl("txtExpirationDateEdit");
strExpirationDate = txtExpirationDateEdit.Text;
if(!ValidateExpirationDate())
{
ToggleTextBoxColor(false,txtExpirationDateEdit);
blnIsValid = false;
}
TextBox txtDescriptionEdit = (TextBox)row.FindControl("txtDescriptionEdit");
strDescription = txtDescriptionEdit.Text;
if(!blnIsValid)
{
this.lblErrorMessage.Text = "Please corrext the data highlighted in yellow";
this.lblErrorMessage.Visible= true;
return;
}
FormatTicker();
//update the data
UpdateData.UpdateOptionEntryFormData(intOptionIDEdit, strSymbol, strCallPut, strUnformattedPrice, dtmExpirationDate, strDescription, strBuyWrite, strTicker, "Manual");
//refresh the grid
this.grdOptions.EditIndex = -1;
DataBindGrid();
}
protected void lkbEdit_Click(object sender, EventArgs e)
{
WebControl wc = (WebControl)sender;
GridViewRow row = (GridViewRow)wc.NamingContainer;
int intIndex = row.RowIndex;
this.grdOptions.EditIndex = intIndex;
DataBindGrid();
}
protected void lkbDelete_Click(object sender, EventArgs e)
{
//get the row that we are sitting on
WebControl wc = (WebControl)sender;
GridViewRow row = (GridViewRow)wc.NamingContainer;
//get the data we need
Label lblRecordID = (Label)row.FindControl("lblOptionID");
int intRecordID = int.Parse(lblRecordID.Text);
//delete the record
DeleteData.DeleteOption(intRecordID);
//refresh the grid
DataBindGrid();
}
protected void lkbCancel_Click(object sender, EventArgs e)
{
this.grdOptions.EditIndex = -1;
}
#endregion

Related

page load with child grids taking too much of time in loading the page

I have three grids - Category grid, Items grid and Sub Items Grid. I have category grid (grdCategories) and for each category there are many items which i bind to child grids (grdItems). For every item there are many sub items which i display in sub child grid (grdSubItems). Now the problem is that page takes too much of time in loading the data. My HTML Code is below:
It takes even minutes to load the data:
ASPX
<asp:GridView ID="grdCategories" runat="server" AutoGenerateColumns="false" DataKeyNames="Category"
CssClass="menu_items" OnRowDataBound="grdCategories_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Panel ID="pnlMealOptionsHeader" runat="server" Width="100%">
<h1>
<a id='<%# Eval("CategoryX")%>'>
<asp:Label ID="lblCategory" runat="server" Text='<%#Eval("Category") %>' Visible="false"></asp:Label>
<asp:Label ID="lblCategoryX" runat="server" Text='<%#Eval("CategoryX") %>'></asp:Label>
</a>
</h1>
</asp:Panel>
<asp:Panel runat="server" ID="pnlMealOptionsBody">
<asp:Label ID="lblCategoryXX" runat="server" CssClass="title_2" Text='<%#Eval("CategoryXX") %>'></asp:Label>
<!--Items in Category -->
<asp:GridView ID="grdItems" runat="server" AutoGenerateColumns="false" CssClass="active-grid"
DataKeyNames="Item" OnRowDataBound="grdItems_RowDataBound" ShowHeader="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblItem" runat="server" Text='<%#Eval("Item") %>' Visible="false"></asp:Label>
<asp:Label ID="lblItemX" CssClass="title" runat="server" Text='<%#Eval("ItemX") %>'></asp:Label>
<asp:Label ID="lblItemXX" CssClass="title" runat="server" Text='<%#Eval("ItemXX") %>' style=" font-size:smaller; font-weight:normal"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="grdSubItems" runat="server" AutoGenerateColumns="false" CssClass=""
DataKeyNames="SubItem" ShowHeader="false" OnRowDataBound="grdSubItems_RowDataBound">
<HeaderStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblItem" runat="server" Text='<%#Eval("Item") %>' Visible="false"></asp:Label>
<asp:Label ID="lblSubItem" runat="server" Text='<%#Eval("SubItem") %>' Visible="false"></asp:Label>
<asp:Label ID="lblNoofOptions" runat="server" Text='<%#Eval("NumofOptions") %>' Visible="false"></asp:Label>
<asp:Label ID="lblSubItemX" CssClass="qty" runat="server" Text='<%#Eval("SubItemX") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" CssClass="price" Text='<%#String.Format("£{0}",Eval("SellingCost")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!--End Items in Category -->
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<table width="900px">
<tr>
<td align="center">
<h1>
No Data Available</h1>
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
Code Behind
Categories Gridview Bind
private void FillCategoriesGrid()
{
DataSet ds = new DataSet();
ShopCategoryMapBL bl = new ShopCategoryMapBL(SessionContext.SystemUser);
bl.FetchForShop(ds, RowId);
grdCategories.DataSource = ds.Tables[0].DefaultView;
grdCategories.DataBind();
}
Items Gridview Bind
protected void grdCategories_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView chkTopings = e.Row.FindControl("grdItems") as GridView;
Label lblCategory = e.Row.FindControl("lblCategory") as Label;
FillItemsGrid(chkTopings, WebHelper.Cast(lblCategory.Text, 0));
}
}
protected void FillItemsGrid(GridView grdItems, int Category)
{
try
{
//int cleanOrder = CargoBag.GetValue("CleanOrder", 0);
DataSet aDataSet = new DataSet();
ItemBL bl = new ItemBL(SessionContext.SystemUser);
bl.FetchForCategory(aDataSet, Category, RowId);
grdItems.DataSource = aDataSet.Tables[0];
grdItems.DataBind();
}
catch (Exception ex) { }
}
Sub Items Gridview Bind
protected void grdItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grdSubItems = e.Row.FindControl("grdSubItems") as GridView;
Label lblItem = e.Row.FindControl("lblItem") as Label;
FillSubItemsGrid(grdSubItems, WebHelper.Cast(lblItem.Text, 0));
}
}
protected void FillSubItemsGrid(GridView grdSubItems, int Item)
{
try
{
//int cleanOrder = CargoBag.GetValue("CleanOrder", 0);
DataSet aDataSet = new DataSet();
SubItemBL bl = new SubItemBL(SessionContext.SystemUser);
bl.FetchForItem(aDataSet, Item);
grdSubItems.DataSource = aDataSet.Tables[0];
grdSubItems.DataBind();
}
catch (Exception ex) { }
}
You need to provide all of your code before we can provide an accurate answer.
For example:
Where SubItemBL is defined?
Also try to see what line is the exact bottleneck.
Is it
bl.FetchForCategory(aDataSet, Category, RowId);
or
grdSubItems.DataBind();
If above line is the bottleneck, note that Gridview binding to a datasource with large number of data is indeedslow. how large is your data?

Accessing DetailsView fields

I've started creating an online quiz. I am using a DetailsView linked to a sqlDataSource.
Here's my code:
<asp:DetailsView ID="QuestionDetails" runat="server" AutoGenerateRows="False" DataKeyNames="QuestionID,QuizID" DataSourceID="SqlDataSource_Quiz">
<Fields>
<asp:TemplateField HeaderText="Text_Eng" SortExpression="Text_Eng" ShowHeader="False">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Text_Eng") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Text_Eng") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Text_Eng") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:RadioButton ID="Option1" AccessKey="1" runat="server" Text='<%# Bind("Opt_1") %>' GroupName="AnswerOptions" AutoPostBack="true" OnCheckedChanged="Option_CheckedChanged" />
<br />
<asp:RadioButton ID="Option2" AccessKey="2" runat="server" Text='<%# Bind("Opt_2") %>' GroupName="AnswerOptions" AutoPostBack="true" OnCheckedChanged="Option_CheckedChanged"/>
<br />
<asp:RadioButton ID="Option3" AccessKey="3" runat="server" Text='<%# Bind("Opt_3") %>' GroupName="AnswerOptions" AutoPostBack="true" OnCheckedChanged="Option_CheckedChanged"/>
<br />
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
Note that i am not displaying all data retrieved from the sqlDataSource (there are other fields/columns as well) in the DetailsView.
Now, in my code behind, i am showing the next record by changing the PageIndex of the DetailsView upon clicking a button (NextButton) but at the same time, i need to retrieve some data of the currently displayed record so I've put the following in the button's click handler:
protected void NextButton_Click(object sender, EventArgs e)
{
try
{
// Save off previous answers
DataRowView dr = (DataRowView)QuestionDetails.DataItem;
// Create Answer object to save values
Answer a = new Answer();
a.QuestionID = dr["QuestionID"].ToString();
a.CorrectAnswer = dr["CorrectAnswer"].ToString();
a.UserAnswer = selectedOptionRB.AccessKey.ToString();
ArrayList al = (ArrayList)Session["userAnswers"];
al.Add(a);
Session.Add("userAnswers", al);
}
catch (Exception ex)
{
Label2.Text = "Exception!";
}
if (QuestionDetails.PageIndex == QuestionDetails.PageCount - 1)
{
NextButton.Enabled = false;
}
else
{
QuestionDetails.PageIndex += 1;
NextButton.Enabled = false;
}
if (QuestionDetails.PageIndex == QuestionDetails.PageCount - 1)
{
NextButton.Text = "Finish the Quiz";
}
}
So when i run the code, i get "Exception!" displayed in my Label2 which i setup for testing.
What am i doing wrong?

Cannot get the selected Gridrow value on a buttonClick MVC, C#

Im trying to get the values in a specific gridview row when clickin on it or when clicking on a button.
The problem is that nothing happen when i click on the row, Not even when i click on the button.
The rows are unclickable.
Any help
Here my code for the ASPx page.
<%# Page Language="C#"Inherits="System.Web.Mvc.ViewPage<MvcApplication3.Models.Order>" %>
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = ViewData["list"];
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
CheckBox x;
foreach (DataGridItem di in GridView1.Rows)
{
x = (CheckBox)di.FindControl("checkBox1");
if (x.Checked == true)
{
Label5.Text = GridView1.SelectedRow.Cells[2].Text;
}
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Label5.Text = string.Format("YOu selected row{0} with {1} {2}",
GridView1.SelectedIndex + 1,
GridView1.SelectedRow.Cells[0].Text,
GridView1.SelectedRow.Cells[1].Text);
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("ondblclick", "__doPostBack('GridView1','Select$" + e.Row.RowIndex + "');");
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Tillverkning" InsertVisible="False">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("TillverkningsOrder") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Datum" InsertVisible="False">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("OrderDatum") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Antal" InsertVisible="False">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Kundnamn" InsertVisible="False">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("KundNamn") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label ID="Label5" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Lina,
Although i don't have the answer for your problem I have however found a data consistency issue.
When your scrolling through the checkboxes you are overtyping the Label5.Text each time. Therefore the scrolling is pointless as Label5 will only ever show the value of the last Checkbox it found to have been ticked.
May i suggest the following alternative:
CheckBox x;
foreach (DataGridItem di in GridView1.Rows)
{
x = (CheckBox)di.FindControl("checkBox1");
if (x.Checked == true)
{
if(Label5.Text == "")
{Label5.Text = GridView1.SelectedRow.Cells[2].Text;}
else {Label5.Text = Label5.Text + " - " + GridView1.SelectedRow.Cells[2].Text;}
}
}
This will at least append the data onto the string seperating it with " - " if there are more the 1 Checkboxs selected. Feel free to change the separator as required.

Hide asp.net GridView row with condition

This is my grid
<asp:GridView ID="gridProduct" runat="server"
AutoGenerateColumns="false"
ShowFooter="true"
onrowcancelingedit="gridProduct_RowCancelingEdit"
onrowdeleting="gridProduct_RowDeleting" onrowediting="gridProduct_RowEditing"
onrowupdating="gridProduct_RowUpdating"
onrowcommand="gridProduct_RowCommand"
onrowdatabound="gridProduct_RowDataBound">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:Button ID="buttonUpdate" CommandName="Update" runat="server" ToolTip="Update" Text="Update" />
<asp:Button ID="buttonCancel" CommandName="Cancel" runat="server" ToolTip="Cancel" Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="buttonEdit" CommandName="Edit" runat="server" Text="Edit" ToolTip="Edit"/>
<asp:Button ID="buttonDelete" CommandName="Delete" runat="server" Text="Delete" ToolTip="Delete"/>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="buttonAdd" runat="server" Text="Ajouter" CommandName="AddNew" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="#Piece">
<EditItemTemplate>
<asp:Label ID="labelEditPiece" runat="server" Text='<%#Eval("Piece") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="labelItemPiece" runat="server" Text='<%#Eval("Piece") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="dropDownListPartsFooter" runat="server" DataTextField="Nom" DataValueField="ID_AchatTemplate">
</asp:DropDownList>
ControlToValidate="txtBoxPiece" Text="*" ValidationGroup="validaiton"/>--%>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Series">
<EditItemTemplate>
<asp:Label ID="labelEditSeries" runat="server" Text='<%#Eval("Series") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="labelItemSeries" runat="server" Text='<%#Eval("Series") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBoxSeries" runat="server"/>
<asp:RequiredFieldValidator ID="fieldValidSeries" runat="server" ControlToValidate="txtBoxSeries" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
.... </asp:TemplateField>
</Columns>
This is my page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PsaDataSet psaList = new PsaDataSet();
ViewState.Remove("psaList");
ViewState.Add("psaList", psaList);
ViewState.Add("psaUid", Guid.NewGuid());
if (psaList.PsaLink.DefaultView.Count == 0)
{
// Patch for view footer row when no data
PsaDataSet.PsaLinkDataTable tmpList = new PsaDataSet.PsaLinkDataTable();
PsaDataSet.PsaLinkRow tmpItem = tmpList.NewPsaLinkRow();
tmpItem.PsaUid = (Guid)ViewState["psaUid"];
tmpItem.PsaProductUid = Guid.Empty;
tmpItem.ProductId = 1;
tmpItem.Series = "test";
tmpItem.Rev = "test";
tmpItem.Firmware = "test";
tmpList.AddPsaLinkRow(tmpItem);
tmpList.AcceptChanges();
ViewState.Add("series", tmpItem.Series);
gridProduct.DataSource = tmpList;
gridProduct.DataBind();
}
}
else
{
//BindGrid((PsaDataSet)ViewState["psaList"], false);
}
}
private void BindGrid(PsaDataSet psaList, bool mustDataBind)
{
gridProduct.DataSource = psaList.PsaLink;
//if (mustDataBind)
//{
gridProduct.DataBind();
//}
}
This my onrowdatabound="gridProduct_RowDataBound"> method
protected void gridProduct_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["style"] = "display:none";
}
}
}
I want to add a condition (Based whit a test value inserted in page load) in the if(protected void gridProduct_RowDataBound method) for hiding just one time on page load??
Thank Frank!
I belive you can get the DataBoundItem from the row which is a type of "PsaDataSet.PsaLinkRow" and use that you get the ProductId, Series, etc. and do the condition that you require. Also, you have and if condition inside an if condition with the same condition for both. You only need one.

Set selected value of dropdown list in Gridview.RowEditing

I am doing insert/update and delete in gridview. For that I am using ItemTemplate which contains labels to show the values. But when the gridview is in edit mode, the dropdown lists comes in place of that labels. I want to set the selected values of drop down lists to the values of labels. My drop down lists dont have datasource. I am binding dropdown list from 0 to 99. Below is the code for my edit method.
protected void grdUsedCatheters_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
grdUsedCatheters.EditIndex = e.NewEditIndex;
BindCatheterGrid();
DropDownList ddlFrom = (DropDownList)grdUsedCatheters.Rows[e.NewEditIndex].FindControl("ddFrom");
DropDownList ddlTo = (DropDownList)grdUsedCatheters.Rows[e.NewEditIndex].FindControl("ddTo");
BindDropDowns(ddlFrom);
BindDropDowns(ddlTo);
}
catch (Exception ex)
{
if (ex.HelpLink == null)
lblMessage.Text = ex.Message;
else
lblMessage.Text = ex.HelpLink;
lblMessage.CssClass = "ERROR";
}
private void BindDropDowns(DropDownList ddl)
{
for (int i = 0; i <= 99; i++)
ddl.Items.Add(i.ToString());
}
below is the part of markup of my gridview
<asp:TemplateField HeaderText="Cine Run">
<ItemTemplate>
From: <asp:Label ID="lblFrom" runat="server" ><%# Eval("CineRunFrom")%></asp:Label>
To: <asp:Label ID="lblTo" runat="server"><%# Eval("CineRunTo")%></asp:Label>
</ItemTemplate>
<EditItemTemplate>
From: <asp:DropDownList ID="ddFrom" runat="server" Width="50px">
</asp:DropDownList>
To: <asp:DropDownList ID="ddTo" runat="server" Width="50px">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
From: <asp:DropDownList ID="ddFromF" runat="server" Width="50px"> </asp:DropDownList>
To: <asp:DropDownList ID="ddToF" runat="server" Width="50px"> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
}
Retrieve the values of label's before setting grdUsedCatheters.EditIndex = e.NewEditIndex and calling BindCatheterGrid() method and then after populating the DropDownLists set their selected value accordingly. Like this:
protected void grdUsedCatheters_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
Label lblFrom = (Label)grdUsedCatheters.Rows[e.NewEditIndex].FindControl("lblFrom"); //lblFrom is the ID of label
grdUsedCatheters.EditIndex = e.NewEditIndex;
BindCatheterGrid();
DropDownList ddlFrom = (DropDownList)grdUsedCatheters.Rows[e.NewEditIndex].FindControl("ddFrom");
DropDownList ddlTo = (DropDownList)grdUsedCatheters.Rows[e.NewEditIndex].FindControl("ddTo");
BindDropDowns(ddlFrom);
BindDropDowns(ddlTo);
ddlFrom.Text = lblFrom.Text;
}
catch (Exception ex)
{
if (ex.HelpLink == null)
lblMessage.Text = ex.Message;
else
lblMessage.Text = ex.HelpLink;
lblMessage.CssClass = "ERROR";
}
}
Edit
and also change your gridview markup like this:
<asp:TemplateField HeaderText="Cine Run">
<ItemTemplate>
From: <asp:Label ID="lblFrom" runat="server" Text='<%# Eval("CineRunFrom")%>' />
To: <asp:Label ID="lblTo" runat="server" Text='<%# Eval("CineRunTo")%>' />
</ItemTemplate>
...
I think this example will work for you.
First you put hidden field in EditItemTemplate where u have put the Dropdownlist.
Set the value of hidden field as you set the value of label in ItemTemplate
See my code:
<asp:GridView runat="server" ID="gridExample" OnRowEditing="gridExample_RowEditing"
AutoGenerateEditButton="True" AutoGenerateColumns ="false" OnRowCancelingEdit ="gridExample_RowCancelingEdit" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="lblID" Text='<%# Eval("ID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="drpName">
</asp:DropDownList>
<asp:HiddenField runat ="server" ID ="hdnId" Value ='<%# Eval("ID") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="lblName" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox runat ="server" ID="txtName" Text ='<%# Eval("Name") %>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void gridExample_RowEditing(object sender, GridViewEditEventArgs e)
{
gridExample.EditIndex = e.NewEditIndex;
BindGrid();
DropDownList dl=new DropDownList ();
dl = (DropDownList)gridExample.Rows[gridExample.EditIndex].FindControl("drpName");
FillDrops(dl);
HiddenField hdnId = new HiddenField();
hdnId = (HiddenField)gridExample.Rows[gridExample.EditIndex].FindControl("hdnId");
dl.Text = hdnId.Value;
}

Categories

Resources