listview and datalist not updating,inserting - c#

Data entered in textboxes is not getting updated in database. In debug mode I see that text1 and text2 in ItemUpdating event contain the same values as they had before calling ItemUpdating.
Here's my listview control:
<asp:ListView ID="ListView1" runat="server"
onitemediting="ListView1_ItemEditing"
onitemupdating="ListView1_ItemUpdating"
oniteminserting="ListView1_ItemInserting">
//LayoutTemplate removed
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("id")%>'></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%#Eval("text1")%>'></asp:Label>
<asp:LinkButton ID="LinkButton2" CommandName="Edit" runat="server">Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton4" CommandName="Delete" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("id")%>'></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("text1")%>' TextMode="MultiLine" />
<asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("text2")%>' Height="100" TextMode="MultiLine" />
<asp:LinkButton ID="LinkButton1" CommandName="Update" CommandArgument='<%# Eval("id")%>' runat="server">Update</asp:LinkButton>
<asp:LinkButton ID="LinkButton5" CommandName="Cancel" runat="server">Cancel</asp:LinkButton>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine" Height="100"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server" Height="100" TextMode="MultiLine"></asp:TextBox>
<asp:LinkButton ID="LinkButton3" runat="server">Insert</asp:LinkButton>
</InsertItemTemplate>
</asp:ListView>
Codebehind file:
protected void ListView1_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListView1.EditIndex = e.NewEditIndex;
BindList();
}
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
ListViewItem myItem = ListView1.Items[ListView1.EditIndex];
Label id = (Label)myItem.FindControl("Label1");
int dbid = int.Parse(id.Text);
TextBox text1 = (TextBox)myItem.FindControl("Textbox1");
TextBox text2 = (TextBox)myItem.FindControl("Textbox2");
//tried to work withNewValues below, but they don't work, "null reference" error is being thrown
//text1.Text = e.NewValues["text1"].ToString();
//text2.Text = e.NewValues["text2"].ToString();
//odbc connection routine removed.
//i know that there should be odbc parameteres:
comm = new OdbcCommand("UPDATE table SET text1 = '" + text1.Text + "', text2 = '" + text2.Text + "' WHERE id = '" + dbid + "'", connection);
comm.ExecuteNonQuery();
conn.Close();
ListView1.EditIndex = -1;
//here I databind ListView1
}
What's wrong with updating of text1.Text, text2.Text in ItemUpdating event? Should I use e.NewValues property? If so, how to use it?
Thanks in advance for any help.

Pffff. 2 days wasted. Just found out that I forgot to use to use in Page_Load():
if (!IsPostBack)
{
ListView1.DataSource = ds;
ListView1.DataBind();
}

Related

update data in gridview

i want to edit the data in my gridview however it shows me an error that i dont know how to fix. can someone help me out please? here is my aspx page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="ProductName">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ProductName") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="Invalid" ForeColor="Red" ControlToValidate="TextBox1"
ValidationExpression="^[a-zA-Z ]+$"></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductDescription">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("ProductDescription") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("ProductDescription") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Invalid"
ForeColor="Red" ControlToValidate="TextBox2"
ValidationExpression="^[a-zA-Z ]+$"></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText ="ProductImage" DataImageUrlField="ProductImage" SortExpression="ProductImage" ControlStyle-Width ="10">
<ControlStyle Width="50px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="ProductQuantity">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ProductQuantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("ProductQuantity") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ErrorMessage="Invalid" ControlToValidate="TextBox3"
ForeColor="Red" ValidationExpression=^[0-9]*$></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductPrice">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ErrorMessage="Invalid" ControlToValidate="TextBox4"
ForeColor="Red" ValidationExpression=^[0-9]*$></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
<%--<asp:CommandField ShowDeleteButton="true" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkdel" runat="server" Text="Delete" CommandName="Delete"
OnClientClick="return confirm('Confirm Delete?');"></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
here is my code behind:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Finding the controls from Gridview for the row which is going to update
//Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_ID") as Label;
int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox ProductName = GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox;
TextBox ProductDescription = GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;
TextBox ProductQuantity = GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox;
TextBox ProductPrice = GridView1.Rows[e.RowIndex].FindControl("TextBox4") as TextBox;
conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=Authorship;Integrated Security =True");
conn.Open();
//updating the record
SqlCommand cmd = new SqlCommand("Update Products set ProductName='" + ProductName.Text + "',ProductDescription='" + ProductDescription.Text + "',ProductQuantity='" + ProductQuantity.Text + "', ProductPrice='" + ProductPrice + "' where ProductID='" + userid + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
//Call ShowData method for displaying updated data
gvbind();
}
when i try to edit the data it shows me :
Conversion failed when converting the varchar value 'System.Web.UI.WebControls.TextBox' to data type int.
Line 64: //updating the record
Line 65: SqlCommand cmd = new SqlCommand("Update Products set ProductName='" + ProductName.Text + "',ProductDescription='" + ProductDescription.Text + "',ProductQuantity='" + ProductQuantity.Text + "', ProductPrice='" + ProductPrice + "' where ProductID='" + userid + "'", conn);
Line 66: cmd.ExecuteNonQuery();
Line 67: conn.Close();
Line 68: //Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
I think you should write Convert.ToInt32(ProductPrice.Text) instead of ProductPrice in your query.
like this`
SqlCommand cmd = new SqlCommand("Update Products set ProductName='" + ProductName.Text + "',ProductDescription='" + ProductDescription.Text + "',ProductQuantity='" + ProductQuantity.Text + "', ProductPrice='" + Convert.ToInt32(ProductPrice.Text) + "' where ProductID='" + userid + "'", conn);

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

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?

Acessing a datacontrol from a listview in asp.net c

I''ve been working at this for a good while now. I'm simply trying to access something that is in a datalist. I can get items just fine from the PageLoad, even set some dynamic items.. but I can't acess controls from my button click handler.
I've tried other variations such as
ListView1.FindControl("DropDownList1") as DropDownList;
Which gives a NULL.
I've tried
<asp:LinkButton id="addPro" runat="server" CommandArgument='<%# DropDownList1.SelectedItem.Text %>' onCommand ="addPro_Click">Add To Cart</asp:LinkButton>
Which says it can't find the data control in scope.
<asp:ListView ID="ListView1" runat="server"
DataKeyNames="Expr7,Expr1,productNo" DataSourceID="SqlDataSource1">
<AlternatingItemTemplate>
<span style="">
<asp:Label ID="productNameLabel" runat="server"
Text='<%# Eval("productName") %>' />
<br />
<asp:Image runat="server" height = "300" ImageUrl='<%# Eval("img") %>'></asp:Image>
<br />
Description:<br />
<asp:Label ID="itemNotesLabel" runat="server" Text='<%# Eval("itemNotes") %>' />
<br />
stock:
<asp:Label ID="stockLabel" runat="server" Text='<%# Eval("stock") %>' />
<br />
price:
<asp:Label ID="priceLabel" runat="server" Text='<%# "$"+ Eval("price")+".00" %>' />
<br />
Quantitiy: <asp:DropDownList id="DropDownList1" runat="server"> </asp:DropDownList>
<br />
<asp:LinkButton id="addPro" runat="server" CommandArgument='<%# Eval("productNo") %>' onCommand ="addPro_Click">Add To Cart</asp:LinkButton>
<br /><br /><br />
<br /></span>
</AlternatingItemTemplate>
On click
protected void addPro_Click(Object sender, CommandEventArgs e)
{
string addr = "";
string v = Request.QueryString["cat"];
if (v != null)
{
v = "cat=" + v+"&";
}
else
{
v = "";
}
DropDownList stockDD = (DropDownList) FindControl("DropDownList1");
if (stockDD != null)
addr = "~/product.aspx/?" + v + "add=" + e.CommandArgument.ToString() + "&quant=" + stockDD.SelectedItem.Text;
else
addr = "ERROR!";
Response.Redirect(addr+e.CommandArgument.ToString());
ListView1.ItemDataBound += (sa, ea) =>
{
DropDownList stockD = ea.Item.FindControl("DropDownList1") as DropDownList;
Label l = ea.Item.FindControl("Lable12") as Label;
l.Text = stockD.SelectedItem.Text;
addr = "~/product.aspx/?" + v + "add=" + e.CommandArgument.ToString() + "&quant=" + stockD.SelectedItem;
};
// Response.Redirect(addr);
}
Any help in the right direction will help a ton! Thanks!
Try this:
LinkButton lbSender = (LinkButton)sender;
ListViewDataItem lvItem = (ListViewDataItem)(lbSender.Parent);
DropDownList DropDownList1 = lvItem.FindControl("DropDownList1");
ListView.Items is a collection of ListViewDataItem which inherits ListViewItem, which inherits from Control. This means you can find any control in its Controls collection using FindControl. You just have to look at the heirarchy.
Docs for ListView: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.aspx
Docs for ListViewDataItem: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewdataitem.aspx
Docs for ListViewItem: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewitem.aspx
Docs for Control: http://msdn.microsoft.com/en-us/library/system.web.ui.control.aspx

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