Set selected value of dropdown list in Gridview.RowEditing - c#

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;
}

Related

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

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

How Do I Transfer Grid view values to next page

How Do I Transfer Grid view values to next page. Grid view consist one of the text box(txtItemGroup) which values have to be entered by the user dynamically, not from the Data base.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("TestItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Items Group">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("TestItemGroup") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group">
<ItemTemplate>
<asp:TextBox ID="txtItemGroup" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Values">
<ItemTemplate>
<asp:Label ID="lblItemValue" runat="server" Text='<%# Eval("TestItemValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Default Values">
<ItemTemplate>
<asp:Label ID="lblDefaultValues" runat="server" Text='<%# Eval("DefaultValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In your GridView's RowCommand event put in the following code:
if (e.CommandName == "Send")
{
TextBox txt = (TextBox)GridView1.FindControls("txtItemGroup");
Session["ItemGroup"] = txt.Text;
}
In addition to this, put a Button or LinkButton in your GridView's ItemTemplate to send the value of the appropriate Textbox as you have put a TextBox and set it's CommandName property in the .aspx page as:
<asp:Button id="btnSend" runat="server" Text = ">" commandName="Send"/>
And then in the Page_Load event of the page where you want the value of TextBox to be viewed:
if (!IsPostback)
{
Label1.Text = Session["ItemGroup"].ToString();
//or
Label1.Text = (String)Session["ItemGroup"];
}
try this:-
Add a button just below that textbox like this:-
<asp:Button ID="btnsend" Text="Send" runat="server" CommandName="Send" />
In RowCommand event write like this:-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Send")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
TextBox TextBox1 = row.FindControl("txtItemGroup") as TextBox;
Response.Redirect("yourasppage.aspx?txt=" + TextBox1.Text);
}
}
On page load of `yourasppage.aspx' use this code
string txtval = Request.QueryString["txt"];
Hope this will help

Error Populating Dropdownlist in Gridview Footer Template in ASP.NET

I want to implement a cascading dropdownlist in a gridview footer template. My code is given below. I am getting an error message "Object reference not set to an instance of an object."
My ASPX Page
<asp:GridView ID="GridView1" runat="server" Width="950px"
AutoGenerateColumns="false" Font-Names="Segoe UI Symbol"
Font-Size="11pt" AlternatingRowStyle-BackColor="White"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AllowPaging="true" ShowFooter="true" RowStyle-BackColor="#A1DCF2"
OnRowEditing="GridView1_RowEditing" DataKeyNames="ServiceID"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowCreated ="GridView1_RowCreated"
PageSize="20" CellPadding="4">
<Columns>
<%--ServiceID--%>
<asp:TemplateField ItemStyle-Width="100px" HeaderText="ServiceID">
<ItemTemplate>
<asp:Label ID="lblServiceID" runat="server" Text='<%# Eval("ServiceId")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<%--Grand Parent Service --%>
<asp:TemplateField ItemStyle-Width="100px" HeaderText="Grand Parent">
<ItemTemplate>
<asp:Label ID="lblGrandParentService" runat="server" Text='<%# Eval("GrandService")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlGrandParentService" AutoPostBack="true" runat="server" Width="150" onselectedindexchanged="ddlGrandParentService_SelectedIndexChanged">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlGrandParentService" AutoPostBack="true" runat="server" Width="150" onselectedindexchanged="ddlGrandParentService_SelectedIndexChanged">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<%-- Parent Service --%>
<asp:TemplateField ItemStyle-Width="100px" HeaderText="Parent Service">
<ItemTemplate>
<asp:Label ID="lblParentService" runat="server" Text='<%# Eval("ParentServiceName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlParentService" runat="server" Width="150" >
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlParentService" runat="server" Width="150">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void ddlGrandParentService_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlGrandParent = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddlGrandParent.NamingContainer;
if (row != null)
{
if ((row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlParent = (DropDownList)row.FindControl("ddlParentService");
ddlParent.DataSource = GetParentServiceByGrandParent(Convert.ToInt32(ddlGrandParent.SelectedValue));
ddlParent.DataValueField = "ParentServiceID";
ddlParent.DataTextField = "ParentServiceName";
ddlParent.DataBind();
}
}
}
public void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlGrandParent = (DropDownList)e.Row.FindControl("ddlGrandParentService");
ddlGrandParent.DataSource = GetGrandParentService();
ddlGrandParent.DataValueField = "GrandParentServiceID";
ddlGrandParent.DataTextField = "GrandService";
ddlGrandParent.DataBind();
//ddlGrandParent.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
DropDownList ddlParent = (DropDownList)e.Row.FindControl("ddlParentService");
//**Getting error "Object reference not set to an instance of an object."**
ddlParent.DataSource = GetParentServiceByGrandParent (Convert.ToInt32((GridView1.FooterRow.FindControl("ddlGrandParentService") as DropDownList).SelectedItem.Value));
ddlParent.DataValueField = "ParentServiceId";
ddlParent.DataTextField = "ParentServiceName";
ddlParent.DataBind();
}
}
private List<GrandParentService> GetGrandParentService()
{
List<GrandParentService> all = new List<GrandParentService>();
using (HospitalEntities dc = new HospitalEntities())
{
all = dc.GrandParentService.ToList();
}
return all;
}
private List<ParentService> GetParentServiceByGrandParent(int grandParentID)
{
List<ParentService> all = new List<ParentService>();
using (HospitalEntities dc = new HospitalEntities())
{
all = dc.ParentService.Where(a => a.GrandParentServiceID.Equals(grandParentID)).ToList();
}
return all;
}
Please help me. Thanks in advance.
Try changing the line where you set the ddlParent.DataSource to the following:
ddlParent.DataSource = GetParentServiceByGrandParent(Convert.ToInt32(ddlGrandParent.SelectedItem.Value));
You have to load the parent DropDownList from the current EventArgs (like you did few lines above) and not from GridView.FooterRow. And secondly you have loaded the parent control a few lines above.
You cannot reference the GridView1.FooterRow in the RowCreated event because it is not yet created. You should replace the reference with e.Row.
ddlParent.DataSource = GetParentServiceByGrandParent (Convert.ToInt32((GridView1.FooterRow.FindControl("ddlGrandParentService") as DropDownList).SelectedItem.Value));
Should be:
ddlParent.DataSource = GetParentServiceByGrandParent (Convert.ToInt32((e.Row.FindControl("ddlGrandParentService") as DropDownList).SelectedItem.Value));

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?

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.

Categories

Resources