Listview Cannot select last row - c#

i have an asp.net ListView and i want when i click the select linkbutton to select the row and pass the id of the data to a detailsview. It passes the id for all records except the last one. Any reasons why?
<asp:ListView ID="ListView1" runat="server" DataKeyNames="AnswerID" OnSelectedIndexChanging="ListView1_SelectedIndexChanging">
<EmptyDataTemplate>
<table runat="server" style="">
<tr>
<td>
No data was returned.
</td>
</tr>
</table>
</EmptyDataTemplate>
<ItemTemplate>
<tr style="">
<td>
<asp:LinkButton ID="SelectButton" runat="server" CommandName="Select" Text="Select" />
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("AnswerID") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Question" runat="server" Text='<%# Eval("QuestionText") %>' />
</td>
<td>
<asp:Label ID="UserAnswer" runat="server" Text='<%# Eval("UserAnswerTxt") %>' />
</td>
<td>
<asp:Label ID="CorrectAns" runat="server" Text='<%# Eval("CorrectAnswerTxt") %>' />
</td>
<td>
<asp:Image ID="Image1" ImageUrl='<%# Eval("ImagePath") %>' Width="48" Height="48"
runat="server" />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="">
<th runat="server">
</th>
<th runat="server">
AnswerID
</th>
<th runat="server">
QuestionText
</th>
<th runat="server">
UserAnswerTxt
</th>
<th runat="server">
CorrectAnswerTxt
</th>
<th runat="server">
</th>
<th runat="server">
</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
</td>
</tr>
</table>
</LayoutTemplate>
<SelectedItemTemplate>
<tr style="">
<td>
<asp:LinkButton ID="SelectButton" runat="server" CommandName="Select" Text="Select" />
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("AnswerID") %>'></asp:Label>
</td>
<td>
<asp:Label ID="Question" runat="server" Text='<%# Eval("QuestionText") %>' />
</td>
<td>
<asp:Label ID="UserAnswer" runat="server" Text='<%# Eval("UserAnswerTxt") %>' />
</td>
<td>
<asp:Label ID="CorrectAns" runat="server" Text='<%# Eval("CorrectAnswerTxt") %>' />
</td>
<td>
<asp:Image ID="Image1" ImageUrl='<%# Eval("ImagePath") %>' Width="48" Height="48"
runat="server" />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="False"
DataSourceID="SqlDataSource1">
<Fields>
<asp:BoundField DataField="AnswerID" HeaderText="AnswerID" SortExpression="AnswerID" />
<asp:BoundField DataField="AnswerExplanation" HeaderText="AnswerExplanation" SortExpression="AnswerExplanation" />
<asp:BoundField DataField="SuggestionText" HeaderText="SuggestionText" SortExpression="SuggestionText" />
<asp:BoundField DataField="LessonID" HeaderText="LessonID" SortExpression="LessonID" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ErDiagID], [AnswerID], [LessonID], [AnswerExplanation], [SuggestionText] FROM [ErrorDiagnosis] WHERE ([AnswerID] = #AnswerID)">
<SelectParameters>
<asp:ControlParameter ControlID="ListView1" Name="AnswerID" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
protected void Page_Load(object sender, EventArgs e)
{
Panel p = (Panel)Master.FindControl("Panel1");
if (p != null)
{
p.Visible = false;
}
ArrayList al = (ArrayList)Session["AnswerList"];
if (!Page.IsPostBack)
{
ListView1.DataBind();
}
if (al == null)
{
Response.Redirect("~/Default.aspx");
}
SqlConnection connection = null;
try
{
ListView1.DataSource = al;
//ListView1.SelectedIndex = ListView1.Items.Count - 1;
ListView1.DataBind();
//ListView1.SelectedIndex = ListView1.Items.Count - 1;
ListView1.SelectedIndex = -1;
if (IsPostBack == false)
{
double questions = al.Count;
double correct = 0.0;
for (int i = 0; i < al.Count; i++)
{
Answer a = (Answer)al[i];
if (a.Result == Answer.ResultValue.Correct)
{
correct++;
}
}
//foreach (ListViewItem item in resultGrid.Items)
//{
// Label cor = (Label)item.FindControl("CorrectAns");
// Label useran = (Label)item.FindControl("UserAnswer");
// if (cor.Text != useran.Text)
// {
// useran.Font.Bold = true;
// }
//}
double score = (correct / questions) * 100;
Scorelbl.Text = string.Format("{0:0.##}", score) + "%";
if (score >= 80 && score < 100)
{
resultext.Text = "Μπράβο " + Profile.UserName + "!!!";
}
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
SqlDataSource userQuizDataSource = new SqlDataSource();
userQuizDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
userQuizDataSource.InsertCommand = "INSERT INTO [UserQuiz] ([QuizID], [DateTimeComplete], [Score], [UserName]) VALUES (#QuizID, GETDATE(), #Score, #UserName)";
userQuizDataSource.InsertParameters.Add("QuizID", Session["QuizID"].ToString());
userQuizDataSource.InsertParameters.Add("Score", score.ToString());
userQuizDataSource.InsertParameters.Add("UserName", User.Identity.Name);
int rowsAffected = userQuizDataSource.Insert();
connection.Close();
if (rowsAffected == 0)
{
errorLabel.Text = "";
}
}
}
catch (Exception exp)
{
//throw new Exception(exp.ToString(), exp);
Response.Redirect("~/Default.aspx");
}
}
protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
ListView1.SelectedIndex = e.NewSelectedIndex;
string id = ListView1.SelectedDataKey.Value.ToString();
SqlDataSource1.SelectParameters["AnswerID"].DefaultValue = id;
ListView1.DataBind();
}

Try this to get the selected Rows value
ListView1.SelectedIndex = e.NewSelectedIndex;
string id=ListView1.SelectedDataKey.Value.ToString();
//Then pass the id's value
ListView1.DataBind();
Hope it helps.

Related

How to delete a row from GridView without affecting the Database

I am populating a Gridview using a form with the help of AJAX.
I want to add a delete button to each row and whendelet button is clicked that row should be deleted from GridView (not hidden).
Here is my aspx code:
<asp:Content ID="Content2" ContentPlaceHolderID="Nav" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<table>
<tr>
<td class="auto-style1">
<asp:Label ID="LabelFirstName" runat="server" Text="First Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBoxFirstName" runat="server" CssClass="auto-style2"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">
<asp:Label ID="LabelLastName" runat="server" Text="Last Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBoxLastName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<br /><br />
<asp:Button ID="ButtonSearch" runat="server" Text="Search" CssClass="auto-style3" Width="93px" OnClick="ButtonSearch_Click" />
<br /><br />
<asp:Label ID="LabelNoRows" runat="server" Text="Sorry, we couldn't find any data with this Name." Visible="false" ForeColor="Red"></asp:Label>
<asp:Panel ID="PanelAbsenceInfo" runat="server" Visible="false">
<table>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelFname" runat="server" Text="First Name:"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetFirstName" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelLname" runat="server" Text="Last Name"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetLname" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelEmail" runat="server" Text="Email"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetEmail" runat="server"></asp:Label>
</td>
</tr>
<asp:UpdatePanel ID="UpdatePanelInfo" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelPersonal" runat="server" Text="Personal Days Approved" ></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetPersonal" runat="server" ></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelOther" runat="server" Text="Other Days Approved"></asp:Label>
</td>
<td>
<asp:Label ID="LabelGetOther" runat="server" ></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style4">
<asp:Label ID="LabelTotalDays" runat="server" Text="Total Days Approved" ></asp:Label>
</td>
<td>
<asp:Label ID="LabelgetTotaldays" runat="server" ></asp:Label>
</td>
</tr>
</table>
<br /><br />
<asp:GridView ID="GridViewViewAllRequests" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowCommand="GridViewViewAllRequests_RowCommand">
<Columns>
<asp:BoundField DataField="scrap" Visible ="false" />
<asp:BoundField DataField="isApproved" Visible="false" />
<asp:BoundField HeaderText="Date of Absence" DataField="requestedDate" DataFormatString="{0:MM/dd/yyyy}" />
<asp:BoundField HeaderText="Rotation Period" DataField="rotationPeriod" />
<asp:BoundField HeaderText="Reason" DataField="reason" />
<asp:BoundField HeaderText="Days Missed" DataField="daysMissed" />
<asp:BoundField HeaderText="Department" DataField="departmentName" />
<asp:BoundField HeaderText="Course" DataField="courseName" />
<asp:TemplateField HeaderText="Approved/Declined">
<ItemTemplate>
<asp:Label ID="LabelApproveorDecline" runat="server" Text='<%# Eval("isApproved") == null ? "Decision not yet made." : ((bool)Eval("isApproved") ? "Approved" : "Declined") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Scrap/Undo">
<ItemTemplate>
<asp:Button ID="ScrapButton" CommandArgument='<%# Eval("id") %>' runat="server" Text="Scrap" CommandName="Scrap" Visible='<%# !(bool)Eval("scrap") %>' />
<asp:Button ID="UndoButton" CommandArgument='<%# Eval("id") %>' runat="server" Text="Undo" CommandName="Undo" Visible='<%# (bool)Eval("scrap") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<br /><br />
</asp:Content>
And here is my cs code:
public partial class AbsenceRequestMonitor : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
DoAction();
}
public Boolean ScraptheRequest(int id, bool action)
{
bool success = false;
success = DBOperation.ScrapAbsencedate(id, action);
return success;
}
protected void GridViewViewAllRequests_RowCommand(object sender, GridViewCommandEventArgs e)
{
//Determine the RowIndex of the Row whose Button was clicked.
int id = Convert.ToInt32(e.CommandArgument);
//Get the value of column from the DataKeys using the RowIndex.
// int id = Convert.ToInt32(GridViewViewAllRequests.DataKeys[rowIndex].Values[0]);
if(e.CommandName == "Scrap")
{
ScraptheRequest(id, true);
}
else if(e.CommandName == "Undo")
{
ScraptheRequest(id, false);
}
DoAction();
UpdatePanelInfo.Update();
}
public void DoAction()
{
string firstName = null;
string lastName = null;
firstName = TextBoxFirstName.Text.ToString();
lastName = TextBoxLastName.Text.ToString();
double PdCount = 0;
double OtherCount = 0;
if (firstName != null && lastName != null)
{
//gets student data from the Student Form
List<AbsenceMonitorData> l_studentAbsenceInfo = DBOperation.getStudentAbsenceInfo(firstName, lastName);
AbsenceMonitorData studentAbsenceInfo = l_studentAbsenceInfo.FirstOrDefault();
PdCount += l_studentAbsenceInfo.Where(x => x.reason == "Personal Day").Where(y => y.isApproved == true).Where(z => z.scrap == false).Select(a => a.daysMissed).Sum();
OtherCount += l_studentAbsenceInfo.Where(x => x.reason != "Personal Day").Where(y => y.isApproved == true).Where(z => z.scrap == false).Select(a => a.daysMissed).Sum();
GridViewViewAllRequests.DataSource = l_studentAbsenceInfo;
GridViewViewAllRequests.DataBind();
if (l_studentAbsenceInfo.Count > 0)
{
LabelGetPersonal.Text = PdCount.ToString();
LabelGetOther.Text = OtherCount.ToString();
LabelgetTotaldays.Text = (PdCount + OtherCount).ToString();
LabelGetFirstName.Text = studentAbsenceInfo.firstName.ToString();
LabelGetLname.Text = studentAbsenceInfo.lastname.ToString();
LabelGetEmail.Text = studentAbsenceInfo.studentEmail.ToString();
PanelAbsenceInfo.Visible = true;
LabelNoRows.Visible = false;
}
else
{
LabelNoRows.Visible = true;
}
}
}
}
Right now i was using the Scrap/Undo button which i want to replace it with a Delete button.
Also when i delete the row the count should be affected. (ie. Personal Days Approved, Other Days Approved and Total Days Approved)
The image shows that when i type the name and hit search, GridView is obtained.
I need to be able to delete rows from that gridview.
GridView

Change table row text and bgcolor on a listview value asp.net C

I have a listview and I am trying to change the text color and background color depending on the value of "callswaiting". This is written in C#.
I am trying to accomplish this:
If(Eval("availableAgents") < 1); Then
; If(Eval("callsWaiting" > 2) ,Then );
{
tblSheet.Style.Add("color", "black");
tblSheet.Style.Add("background-color", "red");
}
Else;
{
tblSheet.Style.Add("color", "black");
tblSheet.Style.Add("background-color", "orange");
}
End If;
Else;
{
tblSheet.Style.Add("color", "white");
tblSheet.Style.Add("background-color", "green");
}
End If;
Just stumped on how to update this to ASPX and C#.
My ASPX code is:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:ListView ID="ListView1" runat="server" DataSourceID="con_csq_agentDB" onitemdatabound="ListView1_ItemDataBound">
<AlternatingItemTemplate>
<tr id="MainTableRow" style="background-color: #ADADAD;">
<td style="background-color: gray; color: whitesmoke;">
<asp:Label ID="csqnameLabel" runat="server" Text='<%# Eval("csqname") %>' />
</td>
<td>
<asp:Label ID="callswaitingLabel" runat="server" Text='<%# Eval("callswaiting") %>' />
</td>
<td>
<asp:Label ID="convoldestcontactLabel" runat="server" Text='<%# Eval("convoldestcontact") %>' />
</td>
<td>
<asp:Label ID="loggedinagentsLabel" runat="server" Text='<%# Eval("loggedinagents") %>' />
</td>
<td>
<asp:Label ID="availableagentsLabel" runat="server" Text='<%# Eval("availableagents") %>' />
</td>
<td>
<asp:Label ID="talkingagentsLabel" runat="server" Text='<%# Eval("talkingagents") %>' />
</td>
</tr>
</AlternatingItemTemplate>
<ItemTemplate>
<tr id="MainTableRow" style="background-color: #DCDCDC; color: #000000;">
<td style="background-color: gray; color: whitesmoke;">
<asp:Label ID="csqnameLabel" runat="server" Text='<%# Eval("csqname") %>' />
</td>
<td>
<asp:Label ID="callswaitingLabel" runat="server" Text='<%# Eval("callswaiting") %>' />
</td>
<td>
<asp:Label ID="convoldestcontactLabel" runat="server" Text='<%# Eval("convoldestcontact") %>' />
</td>
<td>
<asp:Label ID="loggedinagentsLabel" runat="server" Text='<%# Eval("loggedinagents") %>' />
</td>
<td>
<asp:Label ID="availableagentsLabel" runat="server" Text='<%# Eval("availableagents") %>' />
</td>
<td>
<asp:Label ID="talkingagentsLabel" runat="server" Text='<%# Eval("talkingagents") %>' />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" data-height='100%'>
<tr runat="server" style="background-color: #113C77; color: #000000;">
<th runat="server"></th>
<th runat="server">Calls waiting</th>
<th runat="server">Current Wait</th>
<th runat="server">Agents Logged in</th>
<th runat="server">Ready</th>
<th runat="server">Talking</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
My C# code is:
public partial class csq_agent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ListView1.DataSourceID = con_csq_agentDB.UniqueID;
}
}
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataitem = (ListViewDataItem)e.Item;
int callswaiting = (int)DataBinder.Eval(dataitem.DataItem, "callswaiting");
if (callswaiting == 3)
{
HtmlTableRow cell = (HtmlTableRow)e.Item.FindControl("MainTableRow");
cell.BgColor = "Red";
}
}
}

.NET ListView not populating on control selection

I have a ListView in .NET that is hooked up to various CRUD methods, the select method that accepts a value doesn't seem to be working. The Data Source is supposed to be taking the value from a drop down list control, taking the selected value. when I do the configure data source method in visual studio, I select this method for my select operation:
EntReqList_byID(Int32 programID), returns List<EntranceRequirementInfo>
Then when I define parameters in the next part of the wizard, I pick control as a parameter source, with the control ID set to CertificateList, which shows the programID as the parameter from CertificateList.SelectedValue.
When I run the page, and select an item from the CertificateList, and click "Show Program", all my data is pulled except for that in the list view. My code is as follows:
The top of my page:
Please select the program credential type:
<asp:DropDownList ID="InitialCredential" runat="server" AutoPostBack="True" OnSelectedIndexChanged="InitialCredential_SelectedIndexChanged">
<asp:ListItem>[Select]</asp:ListItem>
<asp:ListItem>Certificate</asp:ListItem>
<asp:ListItem>Diploma</asp:ListItem>
<asp:ListItem>Degree</asp:ListItem>
</asp:DropDownList>
</p>
<p>
Please select a program:
<asp:DropDownList ID="CertificateList" runat="server" DataSourceID="CertificateODS" DataTextField="ProgramName" DataValueField="ProgramID" Visible="false"></asp:DropDownList>
<asp:DropDownList ID="DiplomaList" runat="server" DataSourceID="DiplomaListODS" DataTextField="ProgramName" DataValueField="ProgramID" Visible="false"></asp:DropDownList>
<asp:DropDownList ID="DegreeList" runat="server" DataSourceID="DegreeListODS" DataTextField="DegreeName" DataValueField="DegreeID" Visible="false"></asp:DropDownList>
</p>
<p>
<asp:LinkButton ID="ShowUpdateFields" runat="server" OnClick="ShowUpdateFields_Click">Show Program</asp:LinkButton>
</p>
My ListView:
<asp:ListView ID="EntReqListView" runat="server" DataSourceID="EntranceReqODS" InsertItemPosition="LastItem">
<AlternatingItemTemplate>
<tr style="">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
</td>
<td>
<asp:Label ID="ProgramIDLabel" runat="server" Text='<%# Eval("ProgramID") %>' />
</td>
<td>
<asp:Label ID="CourseIDLabel" runat="server" Text='<%# Eval("CourseID") %>' />
</td>
<td>
<asp:Label ID="CourseNameLabel" runat="server" Text='<%# Eval("CourseName") %>' />
</td>
<td>
<asp:Label ID="MarkLabel" runat="server" Text='<%# Eval("Mark") %>' />
</td>
</tr>
</AlternatingItemTemplate>
<EditItemTemplate>
<tr style="">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:TextBox ID="ProgramIDTextBox" runat="server" Text='<%# Bind("ProgramID") %>' />
</td>
<td>
<asp:TextBox ID="CourseIDTextBox" runat="server" Text='<%# Bind("CourseID") %>' />
</td>
<td>
<asp:TextBox ID="CourseNameTextBox" runat="server" Text='<%# Bind("CourseName") %>' />
</td>
<td>
<asp:TextBox ID="MarkTextBox" runat="server" Text='<%# Bind("Mark") %>' />
</td>
</tr>
</EditItemTemplate>
<EmptyDataTemplate>
<table runat="server" style="">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<InsertItemTemplate>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />
</td>
<td>
<asp:TextBox ID="ProgramIDTextBox" runat="server" Text='<%# Bind("ProgramID") %>' />
</td>
<td>
<asp:TextBox ID="CourseIDTextBox" runat="server" Text='<%# Bind("CourseID") %>' />
</td>
<td>
<asp:TextBox ID="CourseNameTextBox" runat="server" Text='<%# Bind("CourseName") %>' />
</td>
<td>
<asp:TextBox ID="MarkTextBox" runat="server" Text='<%# Bind("Mark") %>' />
</td>
</tr>
</InsertItemTemplate>
<ItemTemplate>
<tr style="">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
</td>
<td>
<asp:Label ID="ProgramIDLabel" runat="server" Text='<%# Eval("ProgramID") %>' />
</td>
<td>
<asp:Label ID="CourseIDLabel" runat="server" Text='<%# Eval("CourseID") %>' />
</td>
<td>
<asp:Label ID="CourseNameLabel" runat="server" Text='<%# Eval("CourseName") %>' />
</td>
<td>
<asp:Label ID="MarkLabel" runat="server" Text='<%# Eval("Mark") %>' />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="">
<th runat="server"></th>
<th runat="server">ProgramID</th>
<th runat="server">CourseID</th>
<th runat="server">CourseName</th>
<th runat="server">Mark</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<SelectedItemTemplate>
<tr style="">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
</td>
<td>
<asp:Label ID="ProgramIDLabel" runat="server" Text='<%# Eval("ProgramID") %>' />
</td>
<td>
<asp:Label ID="CourseIDLabel" runat="server" Text='<%# Eval("CourseID") %>' />
</td>
<td>
<asp:Label ID="CourseNameLabel" runat="server" Text='<%# Eval("CourseName") %>' />
</td>
<td>
<asp:Label ID="MarkLabel" runat="server" Text='<%# Eval("Mark") %>' />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
My Code behind:
protected void InitialCredential_SelectedIndexChanged(object sender, EventArgs e)
{
//display programs DDL based on credential choice
if(InitialCredential.SelectedValue == "Certificate")
{
CertificateList.Visible = true;
DiplomaList.Visible = false;
DegreeList.Visible = false;
}
else if (InitialCredential.SelectedValue == "Diploma")
{
CertificateList.Visible = false;
DiplomaList.Visible = true;
DegreeList.Visible = false;
}
else if (InitialCredential.SelectedValue == "Degree")
{
CertificateList.Visible = false;
DiplomaList.Visible = false;
DegreeList.Visible = true;
}
else
{
CertificateList.Visible = false;
DiplomaList.Visible = false;
DegreeList.Visible = false;
}
}
protected void CredentialType_SelectedIndexChanged(object sender, EventArgs e)
{
switch (CredentialType.SelectedValue)
{
case "Diploma":
{
entrance_req.Visible = true;
degree_link.Visible = false;
degree_pathways.Visible = true;
}
break;
case "Certificate":
{
entrance_req.Visible = true;
degree_link.Visible = false;
degree_pathways.Visible = false;
}
break;
case "Degree":
{
entrance_req.Visible = false;
degree_link.Visible = true;
degree_pathways.Visible = false;
}
break;
default:
{
entrance_req.Visible = false;
degree_link.Visible = false;
degree_pathways.Visible = false;
}
break;
}
}
protected void ShowUpdateFields_Click(object sender, EventArgs e)
{
show_update_form.Visible = true;
if (InitialCredential.SelectedValue == "Certificate")
{
DiplomaCertificate certificate = new DiplomaCertificate();
PathwaysController controller = new PathwaysController();
certificate = controller.CertificateProgram_byID(int.Parse(CertificateList.SelectedValue));
ProgramName.Text = certificate.ProgramName;
CategoryList.SelectedValue = certificate.CategoryID.ToString();
CredentialType.SelectedValue = "Certificate";
ProgramLength.Text = certificate.ProgramLength;
ProgramLink.Text = certificate.ProgramLink;
Activated.Checked = certificate.Activated;
WorkOutdoors.Checked = certificate.WorkOutdoors;
ShiftWork.Checked = certificate.ShiftWork;
Travel.Checked = certificate.WorkTravel;
}
}
Is there something I am missing to make it get the programID, and populate the data?

Why DropDownList value is missing during postback?

I have a DropDownList whose value is missing when I trigger post-back. Here my aspx, JavaScript and C# code.
Javascript:
<script type="text/javascript">
function stfocus(event) {
if (event.keyCode == 13) {
document.getElementById('tbfrompalletno').focus();
}
}
function tblocenter(event) {
if (event.keyCode == 13) {
__doPostBack('__Page', 'save');
}
}
</script>
ASPX:
<table>
<tr>
<td colspan="2" style="text-anchor: middle; text-align: center; border: thin solid #000000; background-color: #CCCCCC;">
<asp:Label ID="lblheader" runat="server" Text="Partial Pallet Transfer"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: left">
<asp:Label ID="Label_ErrorMsg" runat="server" Text="" BackColor="Red" ForeColor="White" />
<asp:Label ID="Label_Info" runat="server" Text="" BackColor="Green" ForeColor="White" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblwhscode" runat="server" Text="WHS Code:"></asp:Label>
</td>
<td>
<asp:DropDownList ID="cbwhscode" runat="server"
DataSourceID="sql_whs_code" DataTextField="whs_name" DataValueField="whs_code">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblfromloc" runat="server" Text="From Location:"></asp:Label>
</td>
<td>
<asp:TextBox ID="tbfromloc" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblfrompalletno" runat="server" Text="From Pallet:"></asp:Label>
</td>
<td>
<asp:TextBox ID="tbfrompalletno" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClick="btnsubmit_Click" UseSubmitBehavior="false" />
<asp:Button ID="btnback" runat="server" Text="Back" OnClick="btnback_Click" UseSubmitBehavior="false" />
<asp:Button ID="btnhome" runat="server" Text="Home" OnClick="btnhome_Click" UseSubmitBehavior="false" />
</td>
</tr>
</table>
<asp:SqlDataSource ID="sql_whs_code" runat="server" ConnectionString="<%$ ConnectionStrings:infologConnection %>"
SelectCommand="sp_select_auth_whs_code" SelectCommandType="StoredProcedure" OnSelecting="sql_whs_code_Selecting">
<SelectParameters>
<asp:Parameter Name="group_id" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
C# :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.tbfromloc.Attributes.Add("onkeydown", "javascript:stfocus(event);");
this.tbfrompalletno.Attributes.Add("onkeydown", "javascript:tblocenter(event);");
ViewState["language"] = (string)Session["language"];
ViewState["group_id"] = (string)Session["group_id"];
this.loadsetting();
this.cbwhscode.DataBind();
if (this.cbwhscode.Items.Count > 0)
{
ListItem Check = this.cbwhscode.Items.FindByValue(Session["default_whs_code"].ToString());
if ((Check != null) && this.cbwhscode.Items.Contains(Check))
{
this.cbwhscode.SelectedValue = Session["default_whs_code"].ToString();
}
}
this.tbfromloc.Focus();
}
string parameter = Request["__EVENTARGUMENT"];
if (parameter = "save" ) this.btnsubmit_Click(sender, e);
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
this.Label_ErrorMsg.Text = "";
this.Label_Info.Text = "";
string i_whs_code = this.cbwhscode.SelectedValue;
string i_pack_id = this.tbfrompalletno.Text;
string i_loc_code = this.tbfromloc.Text;
Tuple<bool, int, string> result = RF03BLL_Transfer.rf_partial_transfer_check_loc_pallet(i_whs_code, i_pack_id, i_loc_code);
bool o_succeed = result.Item1;
int o_msg_num = result.Item2;
string o_add_info = result.Item3;
if (o_succeed)
{
string strPost = "whscode=" + HttpUtility.UrlEncode(i_whs_code) +
"&palletno=" + HttpUtility.UrlEncode(i_pack_id) +
"&loccode=" + HttpUtility.UrlEncode(i_loc_code);
string path = "~/RF03F_Transfer/RF030202F_TransferPartialAddPacking.aspx?";
path += strPost;
Response.Redirect(path);
}
else
{
this.Label_ErrorMsg.Text = Module.getMsg(o_msg_num, ViewState["language"].ToString());
}
}
protected void sql_whs_code_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.Parameters["#group_id"].Value = ViewState["group_id"].ToString();
}
My issue is: why value of DropDownList is missed?

Returning multiple rows in asp:Table from SQL DataSet

Below is a section of my site where the data is being loaded by a sql query in the code behind, which is listed below as well... My question is how can I duplicate the second < tr > in the < table > if there are more than one record returned in the code behind query... Any pointers or tips are appreciated...
--.aspx Table
`
<h2>Rebate Measures</h2>
<asp:Textbox ID="ProjectID" runat="server"></asp:Textbox>
<table border="1">
<tr style="background-color: beige">
<th>Delete</th>
<th>Packet #</th>
<th>EEC Ref #</th>
<th class="auto-style1">PTR Ref #</th>
<th>Residential Measure</th>
<th>PTCS</th>
<th>PTCS Ducts</th>
<th>PTCS Comm</th>
<th>Bus Bar KWh</th>
<th>Saved KWh</th>
<th>Msr Life</th>
<th>BPA Credit Rate</th>
<th>BPAtoFPUD Reimburse</th>
<th># of Units</th>
<th>Unit Type</th>
<th>Funding Source</th>
<th>Bid Cost</th>
<th>Customer Rebate</th>
</tr>
<tr style="background-color:#E0E0E0">
<td>
<asp:ImageButton Style="float:none; width: 20px; padding: 0; display: inline" ToolTip="Delete" OnClick="Delete_Click" ID="ImageButton1" ImageUrl="Images/DeletePage.gif" runat="server"></asp:ImageButton>
</td>
<td>
<asp:DropDownList ID="DropDownList1" CssClass="ddl" Width="60px" OnTextChanged="PacketNum_TextChanged" AutoPostBack="true" runat="server"></asp:DropDownList>
</td>
<td>
<asp:DropDownList CssClass="ddl" ID="DropDownList2" Width="115px" OnTextChanged="EECNum_TextChanged" AutoPostBack="true" runat="server"></asp:DropDownList>
</td>
<td class="auto-style1">
<asp:TextBox ID="TextBox1" Width="100px" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox2" Width="350px" runat="server" Wrap="true" ></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox3" MaxLength="3" Columns="1" runat="server" Width="34px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox4" runat="server" Width="61px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox5" runat="server" Width="59px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox6" runat="server" Width="45px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox7" runat="server" Width="45px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox8" runat="server" Width="30px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox9" ReadOnly="true" runat="server" Width="78px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox10" BackColor="LightPink" runat="server" Width="128px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox11" TextMode="Number" OnTextChanged="PacketNum_TextChanged" AutoPostBack="true" runat="server" Width="40px"></asp:TextBox>
</td>
<td>
<asp:DropDownList ID="DropDownList3" CssClass="ddl" runat="server">
<asp:ListItem Text="EA" Value="EA"></asp:ListItem>
<asp:ListItem Text="SqFt" Value="SqFt"></asp:ListItem>
<asp:ListItem Text="LnFt" Value="LnFt"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:DropDownList ID="DropDownList4" CssClass="ddl" OnTextChanged="PacketNum_TextChanged" AutoPostBack="true" runat="server">
<asp:ListItem Text="EEI" Value="EEI" Selected="True"></asp:ListItem>
<asp:ListItem Text="Self" Value="Self"></asp:ListItem>
<asp:ListItem Text="Delta" Value="Delta"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:TextBox ID="TextBox12" runat="server" Width="63px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox13" runat="server" Width="93px"></asp:TextBox>
</td>
</tr>
</table>
`
--Code Behind Query
string CS = ConfigurationManager.ConnectionStrings["CARD"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
String sql = "Select * from tbl_Measures_New1 Where Project_ID = #ProjectID and Project_ID like 'R%'";
SqlDataAdapter Msrda = new SqlDataAdapter(sql, con);
Msrda.SelectCommand.Parameters.AddWithValue("#ProjectID", ProjectID.Text);
DataSet Msrds = new DataSet();
Msrda.Fill(Msrds, "Msr");
ViewState["SQL"] = sql;
ViewState["Msr"] = Msrds;
if (Msrds.Tables["Msr"].Rows.Count > 0)
{
DataRow Msrdr = Msrds.Tables["Msr"].Rows[0];
AccountSelect.Text = Msrdr["Account_Num"].ToString();
OccCode.Text = Msrdr["Occ_Code"].ToString();
Measure.Text = Msrdr["Measure"].ToString();
Funding.SelectedValue = Msrdr["Funding_Source"].ToString();
PacketNum.Text = Msrdr["FPUD_Packet_No"].ToString();
EECNum.Text = Msrdr["EEC_Ref_Num"].ToString();
PTRNum1.Text = Msrdr["BPA_Ref_Num"].ToString();
VendorList.SelectedValue = Msrdr["Vendor_ID"].ToString();
SecVendorList.SelectedValue = Msrdr["Secondary_Vendor_ID"].ToString();
BidCost.Text = "$" + Msrdr["Measure_Cost"].ToString().Replace(".0000", ".00");
CustomerRebate.Text = "$" + Msrdr["Customer_Rebate"].ToString().Replace(".0000", ".00");
SavedKWh.Text = Msrdr["Saved_Kwh"].ToString();
Busbar.Text = Msrdr["BusBar_Kwh"].ToString();
BPACredit.Text = "$" + Msrdr["BPA_Credit"].ToString().Replace(".0000", ".00");
BPAReimburse.Text = "$" + Msrdr["BPA-FPUD_Reimburse"].ToString().Replace(".0000", ".00");
Units.Text = Msrdr["Measure_Units"].ToString();
if (Units.Text != "")
{
Units.Text = Msrdr["Measure_Units"].ToString();
}
else
{
Units.Text = "1";
}
UnitType.SelectedValue = Msrdr["Unit_Type"].ToString();
MsrLife.Text = Msrdr["Measure_Life"].ToString();
PTCS.Text = Msrdr["PTCS"].ToString();
Ducts.Text = Msrdr["PTCS_Ducts"].ToString();
Comm.Text = Msrdr["PTCS_Comm"].ToString();
}
There are a few ways to do this. Look into the Repeater control if you want to use a table like this, or look into using a GridView and binding your result set to that. (It is possible to have a dropdowns and textboxes inside of a GridView.)
Also, make sure your code validates ProjectID.Text to avoid any potential SQL injection issues!

Categories