Asp.net error in the updatepanel with check box list - updatepanel

I have code to generate check box list dynamically according to some conditions, If check box selected will be disabled vs.
After that will add this check box list control to placeholder in update panel,
Problem doesn't occur at the first time but when i update the criteria to add or remove from check box list , some check boxes disabled but not selected
ASPX Code
<asp:TextBox AutoPostBack="true" ID="txtCount" runat="server" OnTextChanged="txtCount_TextChanged">0</asp:TextBox>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="ph"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
C# Code
protected void Page_Load(object sender, EventArgs e)
{
CheckBoxList ckb = new CheckBoxList();
int maxCount = int.Parse(txtCount.Text);
for (int i = 0; i < maxCount; i++)
{
ListItem li = new ListItem();
li.Text = "CheckBox " + i.ToString();
bool selected = (i % 2 == 0);
li.Selected = selected;
li.Enabled = !selected;
ckb.Items.Add(li);
}
ph.Controls.Add(ckb);
}
protected void txtCount_TextChanged(object sender, EventArgs e)
{
}

Related

Get value of ASP:TextBox when clicking an ASP:Button

I know this is a stupid question, and a simple question, but I feel like I'm going crazy as I can't get this working (even though I've done it a million times before).
I have a text box and a button in my ASP.NET page
<asp:TextBox ID="commentTextBox" inputtype="text" runat="server" CssClass="uk-textarea"></asp:TextBox>
<asp:Button ID="buttonComment" runat="server" CssClass="uk-button uk-button-text" text="Post Comment" OnClick="buttonComment_Click" />
These are a part of a larger set of HTML markup, that is wrapped in a:
<form id="form1" runat="server">
On button click, I do the following (get the value of the text box and post it to a database as a 'comment')
protected void buttonComment_Click(object sender, EventArgs e)
{
try
{
//string commentText = ((TextBox)FindControl("Comment")).Text;
string strDate = Request.Form["commentTextBox"].ToString();
Spark.Comment comment = new Spark.Comment
{
CommentByEmail = Context.User.Identity.Name.ToString(),
CommentDate = DateTime.Now,
SparkId = sparkId,
CommentText = strDate,
};
using (var client = new AmazonLambdaClient(Amazon.RegionEndpoint.APSoutheast2))
{
var request = new InvokeRequest
{
FunctionName = ConfigurationManager.AppSettings["lambdaArnPrefix"] + "lambdaSparkCreateComment",
Payload = JsonConvert.SerializeObject(comment),
InvocationType = InvocationType.RequestResponse
};
var response = client.Invoke(request);
}
Response.Redirect($"SparkDetail?action=comment");
}
catch (Exception ex)
{
sparkCardSingle.Text = ex.ToString();
}
}
I've tried all these variations of getting the value:
string commentText = ((TextBox)FindControl("commentTextBox")).Text
string commentText = Request.Form["commentTextBox"].ToString();
string commentText = CommentText.Text;
But no matter what, I get this error on post back
System.NullReferenceException: Object reference not set to an instance of an object. at APISpark.SparkDetail.Page_Load(Object sender, EventArgs e) in C:\Users\jmatson\Source\Repos\Production-Spark-Website\APISpark\SparkDetail.aspx.cs:line 136
I don't understand. I feel like I've done this code a billion times before and it works. I have no idea why it's not working now.

ASPNet Dropdown List from 0 to quantity available

I'm creating a webform for a Class assignment that essentially allows you to select a quantity from 0 to the amount available for each product. We're using AdventureWorks 2014 as our datasource.
However it only displays the maximum quantity and not from 0 to the max quantity.
I'm just stuck on what to add so it can display 0 to max quantity. Thanks.
I don't have anything in regards to the code behind, it's just the basic:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnOrder_Click(object sender, EventArgs e)
{
}
protected void ddlQuantity_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You can perform binding by handling SelectedIndexChanged event from ddlProductName to fill ddlQuantity items:
ASPX
<asp:DropDownList ID="ddlProductName" runat="server" AutoPostBack="True" DataSourceID="ddlProductNameitems" DataTextField="Name" DataValueField="Name"
OnSelectedIndexChanged="ddlProductName_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="ddlQuantity" runat="server" AutoPostBack="True" ...></asp:DropDownList>
Then use a List collection to store all numbers from 0 to maximum value set by SUM query then bind that List to DropDownList in SelectedIndexChanged event given above:
ASPX.cs (code-behind)
protected void ddlProductName_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> quantities = new List<string>();
int maxQuantity = 0;
// retrieve SUM result from SqlDataSource
// if 'DataSourceSelectArguments.Empty' doesn't work, try other 'DataSourceSelectArguments' options
DataView view = QuantityChoices.Select(DataSourceSelectArguments.Empty) as DataView;
// set maximum quantity from SUM query result
if (view != null)
{
maxQuantity = int.Parse(view.Table.Rows[0]["TotalInventory"].ToString());
}
else
{
// assign maxQuantity from SqlConnection here
}
// add every quantity amount to the list...
for (int i = 0; i <= maxQuantity; i++)
{
quantities.Add(i.ToString());
}
// ... then sort from least value...
quantities.Sort();
// ... and bind the list here!
ddlQuantity.DataSource = quantities;
ddlQuantity.DataBind();
}
NB: System.Data namespace should be added to use DataView component. Note that it may necessary to remove DataSourceID, DataTextField & DataValueField from ddlQuantity to bind corresponding DropDownList with generated list of quantities.

I want to make sure my code meet the standard and security

Am new to ASP.NET and i just developed a simple online examination portal for learning.
I used ADO.NET,MySql and developed in VS 2010.
I have a login page in which user can login and register page for new user.After successful login user is redirected to the question page and i fetch the first question from database.
I populated the question in label and options in Radio Button list.User can select one option and click next button.
In the click event of next button i calculate the marks.
I store all values in session only.When user click next of last question that is 4 user is redirected to result page and print the marks.
This is my code
public partial class Questions : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
if (!IsPostBack)
{
renderQuestions(1);
Session["buttonIndex"] = 1;
Session["Marks"] = 0;
}
}
public void renderQuestions(int index)
{
MySqlConnection con = null;
string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string qry = "SELECT * FROM QUESTIONS WHERE QUESTION_ID="+index+"";
try
{
using (con = new MySqlConnection(conString))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand(qry, con))
{
using (MySqlDataAdapter ada = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
ada.Fill(dt);
if (dt.Rows.Count > 0)
{
clsQuestion ques = new clsQuestion();
ques.QuestionId = Convert.ToInt32(dt.Rows[0][0]);
ques.Question = Convert.ToString(dt.Rows[0][1]);
ques.Option1 = Convert.ToString(dt.Rows[0][2]);
ques.Option2 = Convert.ToString(dt.Rows[0][3]);
ques.Option3 = Convert.ToString(dt.Rows[0][4]);
ques.Option4 = Convert.ToString(dt.Rows[0][5]);
ques.Answer = Convert.ToInt32(dt.Rows[0][6]);
renderQuesAndAnswers(ques);
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
public void renderQuesAndAnswers(clsQuestion quest)
{
lblQuestion.Text = quest.Question;
RadioButtonList1.Items.Clear();
RadioButtonList1.Items.Add(quest.Option1);
RadioButtonList1.Items.Add(quest.Option2);
RadioButtonList1.Items.Add(quest.Option3);
RadioButtonList1.Items.Add(quest.Option4);
Session["QuestionNumber"] = quest.QuestionId ;
Session["Answer"] = quest.Answer;
}
public class clsQuestion
{
private int questionId;
private string question;
private string option1;
private string option2;
private string option3;
private string option4;
private int answer;
public int QuestionId
{
get { return questionId; }
set { questionId = value; }
}
public string Question
{
get { return question; }
set { question = value; }
}
public string Option1
{
get { return option1; }
set { option1 = value; }
}
public string Option2
{
get { return option2; }
set { option2 = value; }
}
public string Option3
{
get { return option3; }
set { option3 = value; }
}
public string Option4
{
get { return option4; }
set { option4 = value; }
}
public int Answer
{
get { return answer; }
set { answer = value; }
}
}
protected void option1_CheckedChanged(object sender, EventArgs e)
{
if (Convert.ToInt32 (Session["Answer"]) == 1)
{
int marks=Convert.ToInt32 (Session["Marks"]);
marks++;
Session["Marks"] = marks;
}
}
protected void option2_CheckedChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(Session["Answer"]) == 2)
{
int marks = Convert.ToInt32(Session["Marks"]);
marks++;
Session["Marks"] = marks;
}
}
protected void option3_CheckedChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(Session["Answer"]) == 3)
{
int marks = Convert.ToInt32(Session["Marks"]);
marks++;
Session["Marks"] = marks;
}
}
protected void option4_CheckedChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(Session["Answer"]) == 4)
{
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
}
protected void btnNext_Click1(object sender, EventArgs e)
{
int buton = Convert.ToInt32(Session["buttonIndex"]);
if (buton < 5)
{
if (RadioButtonList1.SelectedIndex + 1 == Convert.ToInt32(Session["Answer"]))
{
int marks = Convert.ToInt32(Session["Marks"]);
marks++;
Session["Marks"] = marks;
}
Session["buttonIndex"] = Convert.ToInt32(Session["buttonIndex"]) + 1;
renderQuestions(Convert.ToInt32(Session["buttonIndex"]));
if (buton == 4)
{
Server.Transfer("Results.aspx");
Session.RemoveAll();
}
}
}
}
this is my HTML
<form id="form1" runat="server">
<div>
<h3>Please choose the right answer</h3>
</div>
<table class="style1">
<tr>
<td class="style3">
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="lblQuestion" runat="server" Text=""></asp:Label>
</asp:Panel>
</td>
<td class="style4">
</td>
</tr>
<tr>
<td class="style2">
Answers:</td>
<td>
</td>
</tr>
<tr>
<td class="style2">
<asp:Panel ID="Panel2" runat="server">
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
</asp:RadioButtonList>
<asp:RadioButton ID="option1" runat="server" Checked="false" AutoPostBack="True"
GroupName="Option" oncheckedchanged="option1_CheckedChanged" />
<asp:RadioButton ID="option2" runat="server" Checked="false" AutoPostBack="True"
GroupName="Option" oncheckedchanged="option2_CheckedChanged" />
<asp:RadioButton ID="option3" runat="server" Checked="false" AutoPostBack="True"
GroupName="Option" oncheckedchanged="option3_CheckedChanged" />
<asp:RadioButton ID="option4" runat="server" Checked="false" AutoPostBack="True"
GroupName="Option" oncheckedchanged="option4_CheckedChanged" />
</asp:Panel>
</td>
<td>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
</td>
</tr>
<tr>
<td class="style2">
<asp:Button ID="btnNext" runat="server" onclick="btnNext_Click1" Text="Next" />
</td>
<td>
</td>
</tr>
</table>
</form>
I got the result perfect and no issues yet.But i want to make sure am doing the best way and do my code meet the standards and is there any security issues.
Please some one guide me through this if u can.Thanks in advance.

Loading data into a textbox and then changing it

i have made a textbox that gets it's text from a variable linked to a database.
ee from class employee and s from class general both work, and the data inside ee is correct.
when the page loads, the textbox does show the data inside ee.Field but when i change it and click save it doesnt change and doesnt save the new data in my database , i know for sure the the functions.fieldChange() works and that for some reason it doesnt get into the if(field.text!=ee.Field) (i have checked it using a simple label text change).
here is my html:
<asp:TextBox ID="field" runat="server"></asp:TextBox><br />
<asp:Button ID="Save" runat="server" Text="Save" OnClick="saveChanges" />
my asp.net:
string User;
Genral s = new Genral ();
public Employee ee;
protected void Page_Load(object sender, EventArgs e)
{
User = Session["User"].ToString();
ee = s.getEmployee(User);
this.field.Text = ee.Field;
}
protected void saveChanges(object sender, EventArgs e)
{
if (field.Text != ee.Field)
{
s.fieldChange(User, field.Text);
}
}
What doesnt it work? Thanks for the help
You need to check ispostback property in page load, when you hit save button it first called postback so it replace the value with the old one and your newly inserted data lost.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
User = Session["User"].ToString();
ee = s.getEmployee(User);
this.field.Text = ee.Field;
}
}

Pause Mediaelement in Windowos phone 8 if user navigates to the other app or homescreen

I had developed application which plays videos using MediaElement with remote url. Everything works fine videos are also playing nicely.
But the problem I am facing is if user is playing video and user touches windows button on phone. Then my app goes to background and home screen is displayed. now on home screen user touches back button. My app is brought to foreground and video starts loading from beginning. Is there anyway by which I can pause mediaelement so that when user comes back to my app video gets resumed.
One more thing is I can not user MediaLauncher since I want to log some events when user interacts with mediacontrols such as play/pause.
Kindly requesting you all to guide me in this scenario.
Thank You.
you can resume your application via ActivationPolicy attribute to the DefaultTask element inActivationPolicy attribute to the DefaultTask element in WMAppManifest.xml and set the value to “Resume”. For this task, you need to edit the app manifest directly instead of using the manifest editor. To do this, right-click WMAppManifest.xml, click Open with, and then choose XML (Text) Editor.
For Resume can be enabled for XAML apps, Direct3D apps, and Direct3D with XAML apps. The following examples show how the DefaultTask element will look for a XAML app and for a Direct3D app.
<DefaultTask Name="_default" NavigationPage="MainPage.xaml" ActivationPolicy="Resume"/>
<DefaultTask Name="_default" ImagePath="PhoneDirect3DApp1.exe" ImageParams="" ActivationPolicy="Resume"/>
app resume for Windows Phone 8
app resume backstack sample
If this will not help you than you can manual paly and stop your video pleyer like bellow code
XAML
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="0.90*"/>
<RowDefinition Height="0.10*"/>
</Grid.RowDefinitions>
<SSME:SmoothStreamingMediaElement x:Name="video" Grid.Row="0" />
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Orientation="Horizontal" Grid.Row="1">
<Button x:Name="PlayButton" Width="150" Click="PlayButton_Click" Loaded="PlayButton_Loaded"/>
<Button x:Name="StopButton" Content="Stop" Width="100" Click="StopButton_Click" />
<TextBlock x:Name="status"/>
<TextBlock x:Name="currentBitrate"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
</Grid>
C# code:
public partial class VIdeoStraming : PhoneApplicationPage
{
string VideoUrl,StreamingUrl;
public VIdeoStraming()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
VideoUrl = this.NavigationContext.QueryString["parameter0"];
string Manifest="/Manifest";
StreamingUrl = VideoUrl + Manifest;
}
private void PlayButton_Click(object sender, RoutedEventArgs e)
{
//Monitor the state of the content to determine the right action to take on this button being clicked
//and then change the text to reflect the next action
switch (video.CurrentState)
{
case SmoothStreamingMediaElementState.Playing:
video.Pause();
PlayButton.Content = "Play";
break;
case SmoothStreamingMediaElementState.Stopped:
case SmoothStreamingMediaElementState.Paused:
video.Play();
PlayButton.Content = "Pause";
break;
}
}
private void PlayButton_Loaded(object sender, RoutedEventArgs e)
{
switch (video.AutoPlay)
{
case false:
PlayButton.Content = "Play";
break;
case true:
PlayButton.Content = "Pause";
break;
}
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
//This should simply stop the playback
video.Stop();
//We should also reflect the chang on the play button
PlayButton.Content = "Play";
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
video.CurrentStateChanged += new RoutedEventHandler(video_CurrentStateChanged);
video.PlaybackTrackChanged += new EventHandler<Microsoft.Web.Media.SmoothStreaming.TrackChangedEventArgs>(video_PlaybackTrackChanged);
//video.SmoothStreamingSource = new Uri("http://64.120.251.114:1945/live/sharedobjects/layoutvideo/mp4:1311370468970.MP4/Manifest");
video.SmoothStreamingSource = new Uri(StreamingUrl);
video.ManifestReady += new EventHandler<EventArgs>(video_ManifestReady);
}
//when use in mobile device
void video_ManifestReady(object sender, EventArgs e)
{
SmoothStreamingMediaElement ssme = sender as SmoothStreamingMediaElement;
if (ssme == null)
{
return;
}
// Select the highest band of tracks which all have the same resolution.
// maxMobileBitrate depends on the encoding settings
const ulong maxMobileBitrate = 1000000;
foreach (SegmentInfo segment in ssme.ManifestInfo.Segments)
{
foreach (StreamInfo streamInfo in segment.AvailableStreams)
{
if (MediaStreamType.Video == streamInfo.Type)
{
List<TrackInfo> widestBand = new List<TrackInfo>();
List<TrackInfo> currentBand = new List<TrackInfo>();
ulong lastHeight = 0;
ulong lastWidth = 0;
ulong index = 0;
foreach (TrackInfo track in streamInfo.AvailableTracks)
{
index += 1;
string strMaxWidth;
string strMaxHeight;
// If can't find width/height, choose only the top bitrate.
ulong ulMaxWidth = index;
// If can't find width/height, choose only the top bitrate.
ulong ulMaxHeight = index;
// V2 manifests require "MaxWidth", while v1 manifests used "Width".
if (track.Attributes.TryGetValue("MaxWidth", out strMaxWidth) ||
track.Attributes.TryGetValue("Width", out strMaxWidth))
{
ulong.TryParse(strMaxWidth, out ulMaxWidth);
}
if (track.Attributes.TryGetValue("MaxHeight", out strMaxHeight) ||
track.Attributes.TryGetValue("Height", out strMaxHeight))
{
ulong.TryParse(strMaxHeight, out ulMaxHeight);
}
if (ulMaxWidth != lastWidth ||
ulMaxHeight != lastHeight)
{
// Current band is now finished, check if it is the widest.
// If same size, current band preferred over previous
// widest, because it will be of higher bitrate.
if (currentBand.Count >= widestBand.Count)
{
// A new widest band:
widestBand = currentBand;
currentBand = new List<TrackInfo>();
}
}
if (track.Bitrate > maxMobileBitrate)
{
break;
}
// Current track always gets added to current band.
currentBand.Add(track);
lastWidth = ulMaxWidth;
lastHeight = ulMaxHeight;
}
if (0 == widestBand.Count &&
0 == currentBand.Count)
{
// Lowest bitrate band is > maxMobileBitrate.
widestBand.Add(streamInfo.AvailableTracks[0]);
}
else if (currentBand.Count >= widestBand.Count)
{
// Need to check the last band which was constructed.
Debug.Assert(currentBand.Count > 0);
widestBand = currentBand; // Winner by default.
}
Debug.Assert(widestBand.Count >= 1);
streamInfo.RestrictTracks(widestBand);
}
}
}
}
void video_PlaybackTrackChanged(object sender, Microsoft.Web.Media.SmoothStreaming.TrackChangedEventArgs e)
{
currentBitrate.Text = e.NewTrack.Bitrate.ToString();
}
void video_CurrentStateChanged(object sender, RoutedEventArgs e)
{
status.Text = video.CurrentState.ToString();
}
private void imghdrleft_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
NavigationService.GoBack();
}
private void imghdrright_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
NavigationService.Navigate(new Uri("/Planet41VIew/Settings.xaml", UriKind.RelativeOrAbsolute));
}
}