I am making a signin form for a webpage. I have created a multidimensional array with acceptable username/password combinations. I would like to allow the user to move on to the next page only if their username/password combination is found in the array. If they enter a combination that is not found in the array, I want an error to raise and keep them from proceeding to the next page.
I understand that this is not the most effective way to complete this command, but I am learning how to properly use Arrays as part of the foundation to my programming knowledge. I'll paste my code below. I've tried various way to get the page to do what I want, but I can't seem to get it. I get this error: "System.IndexOutOfRangeException: Index was outside the bounds of the array." Here is my code:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
string[,] UserPass = new string[,] {{"user1","pwd1"}, {"user2", "pwd2"}, {"user3","pwd3"}};
void Page_Load(object sender, EventArgs e)
{
}
void btnSignin_Click(object sender, EventArgs e)
{
if(txtSignin.Text == UserPass[1,0] && txtPWD.Text == UserPass[0,1])
{
Response.Redirect("welcome.aspx");
}
else if (txtSignin.Text == UserPass[2, 0] && txtPWD.Text == UserPass[0, 2])
{
Response.Redirect("welcome.aspx");
}
else if (txtSignin.Text == UserPass[3, 0] && txtPWD.Text == UserPass[0, 3])
{
Response.Redirect("welcome.aspx");
}
else
{
Response.Write("Please try again.");
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<p>Sign in with Account</p>
<asp:Panel ID="Pnl1" runat="server">
<br />
<asp:Textbox ID="txtSignin" runat="server" Text="Username" style="width:190px" /><br />
<asp:TextBox ID="txtPWD" runat="server" Text="Password" TextMode="Password" style="width:190px" /><br />
<asp:LinkButton ID="btnSignin" runat="server" Text="Sign in" class="myBtn" OnClick="btnSignin_Click"/><br />
<asp:CheckBox ID="chkRemember" runat="server" Text="Stay signed in" />
</asp:Panel>
<asp:Label ID="lblSignin" runat="server" />
</div>
</form>
</body>
</html>
(also, on a smaller note, is it possible to have the signin/password boxes display text that disappears when the users clicks the textbox?)
Thank you for any help!
There are different options. One is using arrays with a for loop and another is using Linq. I will show you how to do it with arrays.
string[,] UserPass = new string[,] {{"user1","pwd1"}, {"user2.edu", "pwd2"}, {"user3","pwd3"}};
...
bool isFound = false;
for (int i=0; i< UserPass.GetLength(0); i++)
{
//search users row by row
if (UserPass[i, 0] == yourSearchUserid && UserPass[i, 1] == yourSearchPassword)
{
isFound = true;
break;
}
}
//isFound holds the search result.
Related
I am trying to use Visual Studio C# to printscreen, then save the screen capture to a file.
Currently, I am having problems reading from the clipboard.
I have tried using both of the following lines to save a screen capture to the clipboard:
SendKeys.SendWait("+{PRTSC}");
SendKeys.SendWait("{PRTSC}");
However, when I try to save the image using the following lines, I get a Null Reference Exception.
How to do resolve this?
My code below
markup code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Welcome to ASP.NET!
</h2>
1. Copy image data into clipboard or press Print Screen
<br />
2. Press Ctrl+V (page/iframe must be focused):
<br />
<br />
<canvas style="border: 1px solid grey;" id="cc" width="200" height="200">
<script type="text/javascript">
var canvas = document.getElementById("cc");
var ctx = canvas.getContext("2d");
//=== Clipboard ===============================
window.addEventListener("paste", pasteHandler); //chrome
//handler
function pasteHandler(e) {
if (e.clipboardData == false) return false; //empty
var items = e.clipboardData.items;
if (items == undefined) return false;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") == -1) continue; //not image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
paste_createImage(source);
}
}
//draw pasted object
function paste_createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function () {
ctx.drawImage(pastedImage, 0, 0);
}
pastedImage.src = source;
}
</script>
</canvas>
<br />
</div>
<div>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="Go" />
</div>
</form>
</body>
</html>
code-behind
protected void btn_Click(object sender, EventArgs e)
{
var path = new[] { #"C:\Users\A\source\repos\CopyPaste\public",
#"C:\Users\A\source\repos\CopyPaste\public" }.First(p => Directory.Exists(p));
var prefix = "css-social-media-icon-list";
var fileName = Enumerable.Range(1, 100)
.Select(n => Path.Combine(path, $"{prefix}-{n}.png"))
.First(p => !File.Exists(p));
Clipboard.GetImage().Save(fileName, ImageFormat.Png);
Clipboard.SetText($"![image](/public/{Path.GetFileName(fileName)})");
}
I hope this helping... following this example
I'm using the code below to create radio buttons dynamically to a webpage as each set of data is retrieved from a database by iteration. It works well. The only problem is I need these to PostBack so further data can be retrieved depending on which radio button is clicked. I tried doing this with RadioButton controls but these wouldn't position inside of a table cell like the <span> technique does and they wouldn't create through a <span>.
int count = 0;
if (dataReader.HasRows)
{
testLabel1.Text = "dataReader.HasRows: " + dataReader.HasRows;
while (dataReader.Read())
{
count += 1;
htmlString.Append("<table border = '1'>");
htmlString.Append("<tr>");
htmlString.Append("<td>");
htmlString.Append(dataReader["dateTime"] + "<br />" + "<span><input type='radio' id='rd1'/>SOMTEXT </span>" + dataReader["statistics"]");
htmlString.Append("</td>");
htmlString.Append("</tr>");
htmlString.Append("</table>");
htmlString.Append("<br />");
}
test_populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
dataReader.Close();
dataReader.Dispose();
}
}
}
}
I tried adding runat="server" in <span><input type='radio' id='rd1'runat='server'/>SOMTEXT </span> but it didn't create the radio button. Thanks in advance.
Don't know, how to format code in comment. One more again - if you write runat="Server" in your hand-made html, it does nothing, because this code will not be compiled, you just write html answer manually. On the other hand compilation of declarative language (asp.net, razor or any other) makes javascript, you can do it manually too, but B.Gates kindly agreed to do it for you :-)
Asp.Net design
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server" >
<HeaderTemplate>
<table border ="1">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td style="width:200px">
<asp:Label runat="server" ID="Label1"
/>
</td>
<td style="width:200px" >
<asp:RadioButton ID="RadioButton1" runat="server" Checked="false" Text = '<%# Eval("Text") %>' AutoPostBack ="true" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
C# CodeBehind
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int num = 10;
if (Page.IsPostBack)
{
for (int i = 1; i < this.Repeater1.Controls.Count-1; i++)
{
RadioButton r = (RadioButton)this.Repeater1.Controls[i].Controls[3];
if (r.Checked)
{
num=int.Parse(r.Text.Substring(0, r.Text.IndexOf(' ')));
break;
}
}
}
this.Repeater1.DataSource = GetAll(num);
this.Repeater1.DataBind();
}
DataTable GetAll(int count)
{
Random r = new Random();
DataTable dt = new DataTable();
dt.Columns.Add("Text", typeof(string));
DateTime bs = DateTime.Now;
for (int i = 0; i < count; i++)
{
int value = r.Next(3, 10);
dt.Rows.Add(value.ToString() + " rows will be shown");
}
return dt;
}
}
Method GetAll() returns table, having count lines. In each line is text "%i rows will be shown" with random number. Table is bind to data repeater on page load event. If it is postback, number of rows is parsed from text of radiobutton inside repeater row (you can't get it from data table, it is another page, data table is already in GC)
I have done searches for this but could not find an answer that worked.
I am trying to access the asp:TextBox ID="wordList" node details and its keep return count = 0. I have tried two alternate methods as can be seen below in the javascript and do not understand why its not working. Can anyone see the reason?
Many Thanks
Jaie
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Week3.WebForm1" Theme="Theme1"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Grid Details</title>
</head>
<body>
<script lang="javascript" type="text/javascript" >
function ValidateWordList() {
var x = document.getElementById("wordList").innerHTML;
x += "Length" + x.length;
alert(x);
var z = document.getElementById('<%= wordList.ClientID %>').innerHTML;
alert(z);
return false;
}
</script>
<form id="form1" runat="server">
<div class="form1Box">
<br />
<asp:Label ID="lblWord" runat="server" Text="Word(s) of Puzzle:"><asp:TextBox ID="wordList" runat="server" ClientIDMode="Static"/></asp:Label>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorWordList" ControlToValidate="wordList"
CssClass="Validation" runat="server" Text="(Required)" />
<asp:RegularExpressionValidator ID="RegularExpressionValidatorWordList" ControlToValidate="wordList" runat="server" CssClass="Validation"
ValidationExpression="(^[a-zA-Z ,]*$)" ErrorMessage="(The word(s) can only be letters, space or comma's!)"/>
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" Text="Generate Puzzle" runat="server" OnClientClick="return ValidateWordList()"/>
</div>
</form>
</body>
</html>
Are you trying to retrieve whatever value user has entered in the textbox? If so, you are probably looking for:
var x = document.getElementById("wordList").value;
Text fields do not define any inner markup, and their property innerHtml in most cases is just an empty string.
I have been searching around and I am lost on how to do what I am attempting to do.
I am trying to create a form where the first column is a list of names, and the next column is all dropdown lists. The idea is that for each name the user will pic a value. Each name may require two, or three or more values. I want to create a dynamic form where a user can click add in the row and another dropdown list appears.
Ex.
"Name" | Add Button | DropDown
then when I click add...
"Name" | Add Button | DropDown | DropDown
and have it keep going.
I am able to create the form and I have it working creating the dropdown lists. The problem is that I am adding the controls on the ItemCommand of a repeater, so they must be recreated every time. Because of this I cannot find a way to keep the values selected in each dropdown, when I have to recreate them.
Typically no more than two dropdowns are required but there are a few cases where three is needed, and it could arise for more. I would like to keep this dynamic as possible.
I know that if I added the dropdown's in the page Init they would be persisted on the postback, but at least in my design the user has to click add to get another drop down.
Is there a way to capture the data from these dropdowns then reload them every time? Or a better way to achieve this functionality?
Thank You for your help.
Here is some of the asp and code behind that I am using. This is functioning as I wish, but I don't know how to keep the data on a postback, as all of the dropdown lists I add are lost.
ASP:
<table>
<asp:Repeater ID="repChemicals" runat="server" OnItemCommand="repChemicals_OnItemCommand">
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hfNumber" runat="server" />
<%# Eval("ChemicalName") %>
</td>
<td>
<asp:Button runat="server" ID="btnAdd" Text="Add" CommandArgument="ADD" />
</td>
<td>
<div id="divContainer" runat="server">
<asp:DropDownList runat="server" Width="60px" ID="ddlTest"></asp:DropDownList>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Chem> Chemicals = new List<Chem>();
Random rnd = new Random();
for (int z = 0; z <= 10; z++)
{
List<string> t = new List<string>();
Chem a = new Chem()
{
ChemicalName = "Chemical" + z.ToString()
};
Chemicals.Add(a);
}
repChemicals.DataSource = Chemicals;
repChemicals.DataBind();
}
}
public void repChemicals_OnItemCommand(object sender, RepeaterCommandEventArgs e)
{
int number = 0;
foreach (RepeaterItem i in repChemicals.Items)
{
HiddenField hf = (HiddenField)repChemicals.Items[i.ItemIndex].FindControl("hfNumber");
if (i.ItemIndex == e.Item.ItemIndex)
{
if (!string.IsNullOrWhiteSpace(hf.Value))
{
number = Convert.ToInt16(hf.Value) + 1;
}
else
{
number = 1;
}
hf.Value = number.ToString();
}
else
{
if (!string.IsNullOrWhiteSpace(hf.Value))
{
number = Convert.ToInt16(hf.Value);
}
else
{
number = 0;
}
}
for (int x = 0; x < number; x++)
{
DropDownList ddl = new DropDownList();
ddl.Style.Add("width", "60px");
ddl.ID = "ddl" + i.ToString() + x.ToString();
ddl.Style.Add("Margin-right", "3px");
ddl.Attributes.Add("runat", "server");
ddl.DataSource = DataSource();
ddl.DataBind();
Control c = repChemicals.Items[i.ItemIndex].FindControl("divContainer");
c.Controls.Add(ddl);
}
}
Some of the loops are for creating test data. Basically I am storing a number of dynamic controls on each row in a hiddenfield. Then on the item command I loop through all of the rows and recreate all of the previously existing ddl's, and add one to the row that teh command came from.
This isn't exactly answering your question, but it accomplishes your ultimate goal in a less complex way and one that takes advantage of built in ASP.NET controls so maintaining state between postbacks is taken care of for you.
It utilizes jQuery, jQuery UI and a DropDownChecklist plugin.
ASPX
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/ui.dropdownchecklist.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/base/jquery-ui.css"/>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<asp:Repeater ID="repChemicals" runat="server">
<ItemTemplate>
<tr>
<td>
<%# Container.DataItem %>
</td>
<td>
<div id="divContainer" runat="server">
<asp:ListBox ID="lstAttributes" SelectionMode="Multiple" runat="server"></asp:ListBox>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<asp:Button ID="btnPostback" Text="Postback" runat="server"/>
</div>
</form>
</body>
</html>
C#
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PersonAttributes
{
public partial class People : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
repChemicals.ItemCreated += RepChemicalsOnItemCreated;
var chemicals = new[] {"Hydrogen", "Helium", "Lithium", "Beryllium", "Boron"};
if(!IsPostBack)
{
repChemicals.DataSource = chemicals;
repChemicals.DataBind();
}
var dropDownChecklist = "$(document).ready(function () { $('select').dropdownchecklist(); });";
ScriptManager.RegisterStartupScript(this,GetType(),"initDropDownChecklist",dropDownChecklist,true);
}
private void RepChemicalsOnItemCreated(object sender, RepeaterItemEventArgs repeaterItemEventArgs)
{
var lst = repeaterItemEventArgs.Item.FindControl("lstAttributes") as ListBox;
if (lst == null)
return;
lst.DataSource = new[] {"Option 1", "Option 2", "Option 3"};
}
}
}
See it in action at CodeRun.
I have a grid view with multiple select check boxes. I want to return an array of the items that have been selected and put this in a label (comma-separated)
12,34,34,54,54,5
I want it to be parsed and then sent to a query string or send the whole value to the query string.
How do a get multiple selected check boxes and return an array of items?
Try this:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
System.Collections.Generic.List<int> Values = new System.Collections.Generic.List<int> { 1, 2, 3, 4, 5, 6, 7 };
grdTest.DataSource = Values;
grdTest.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
HtmlInputCheckBox chkTest = null;
string SelectedValues = "";
foreach (GridViewRow row in grdTest.Rows)
{
chkTest = (HtmlInputCheckBox) row.FindControl("chkTest");
if (chkTest != null && chkTest.Checked)
{
SelectedValues += (SelectedValues == "" ? chkTest.Value : ", " + chkTest.Value);
}
}
litValues.Text = SelectedValues;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grdTest" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<input id="chkTest" type="checkbox" name="chkTest" runat="server"
value="<%# (int)Container.DataItem %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click" Text="Submit" />
<br />
<asp:Literal ID="litValues" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
<form>
<input type="checkbox" name="check[]" value ="1"/>
<input type="checkbox" name="check[]" value ="2"/>
<input type="checkbox" name="check[]" value ="3"/>
<input type="checkbox" name="check[]" value ="4"/>
</form>
When you try to retrieve the parameter 'check' you get an array of all the values that were selected.
EDIT:
This link should help in retrieving the values in ASP.
ASP.NET : The checkbox and checkboxlist control