There is a requirement of displaying both PackageID, and PackageName in a dropdown, so that customer can select the package for recharge.
As per the current code, PackageName is visbile using DataTextFiled property , which has been set in markup.
Please help to display both PackageID, and Package Name, and go through below codes-
DataBase-
CREATE TABLE [dbo].[PackageMaster](
[PackageID] [int] IDENTITY(1,1) NOT NULL,
[PackageName] [varchar](50) NULL
) ON
[PRIMARY]
Create Proc UspGetPackage
As
Begin
Select PackageID,PackageName from PackageMaster
End
--------------------------------------------------Design-------------------------------
<%# Page Language="C#" AutoEventWireup="true" CodeFile="PackageRequest.aspx.cs" Inherits="PackageRequest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><b>Select Package:</b></td> 
<td>
<asp:DropDownList ID="DDLPackage" runat="server" DataTextField="PackageName" DataValueField="PackageID"></asp:DropDownList>
</td>
</tr>
<tr>
<td><b>Select Sequence:</b></td> 
<td>
<asp:DropDownList ID="DDLPakcageSequence" runat="server" DataTextField="SequenceValue" DataValueField="SequenceID"></asp:DropDownList>
</td>
</tr>
<tr>
<td><asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
----------------------CodeBehind---------------
private DataSet GetData(string SPName, SqlParameter SPParameter)
{
string CS = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlDataAdapter da = new SqlDataAdapter(SPName, con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
if (SPParameter != null)
{
da.SelectCommand.Parameters.Add(SPParameter);
}
DataSet DS = new DataSet();
da.Fill(DS);
return DS;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DDLPackage.DataSource = GetData("UspGetPackage",null);
DDLPackage.DataBind();
ListItem lstPkg = new ListItem("--Select Package--","-1");
DDLPackage.Items.Insert(0,lstPkg);
//DDLPakcageSequence.DataSource = GetData("UspGetPkgSequence",null);
//DDLPakcageSequence.DataBind();
//ListItem pkgsequence = new ListItem("--Select Sequence--", "-1");
//DDLPakcageSequence.Items.Insert(0, pkgsequence);
}
}
Concat two columns in stored procedure.
Select CONCAT(PackageID,' ', PackageName ) AS PackageID_PackageName, PackageID,PackageName from PackageMaster
In .aspx change DataTextField="PackageName" to DataTextField="PackageID_PackageName"
<asp:DropDownList ID="DDLPackage" runat="server" DataTextField="PackageID_PackageName" DataValueField="PackageID"></asp:DropDownList>
Related
Basically it reads the database file on site, I want to then search a name for instance and then it will pop up with all results which are like the searchName and then output that as a table on a web page, this should be triggered by pressing the button and having typed a letter at least I have been fiddling with this for hours can anyone give me some insight on what I'm doing wrong? I'm also using Odbc to create a DNS on my system, this is a small project just need some trouble finding help as the Odbc code works for adding a record and viewing all records but messes up on this page.
Cheers, Josh
<%# Page Language="C#"%>
<%# Import Namespace="System.Data.Odbc" %>
<%
OdbcConnection oConn = new OdbcConnection("DSN=sailors");
oConn.Open();
string str_sql = "select * from MonsterList where MonsterNames like searchName"; // this is an sql string '*' includes all fields from table
OdbcCommand oCmd = new OdbcCommand(str_sql, oConn);
OdbcDataReader oRs = oCmd.ExecuteReader();
%>
<!DOCTYPE html>
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Search Monster</title>
</head>
<body>
<form method="post" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<strong>Search </strong>
</td>
<td>
<asp:TextBox ID="searchName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnSubmit" runat="server" Text="Search" />
</td>
</tr>
</table>
</form>
<table <link rel="displayrecordSS" href="displayrecordSS.css"/>
<%
while(oRs.Read())
{
string str_out = #"<tr valign=""top"">" +
"<td>" + oRs["MonsterNames"] + "</td>" +
"<td>" + oRs["Element"] + "</td>" +
"<td>" + oRs["Weakness"] + "</td>" +
"</tr>" +
#"<tr bgcolor=""#ff0000""><td height=""1"" colspan=""3""></td></tr>";
Response.Write(str_out);
}
%>
</body>
</html>
<%
oRs.Close();
oRs = null;
oCmd.Dispose();
oCmd = null;
oConn.Close();
oConn.Dispose();
oConn = null;
%>
Working Add Page
<%# Page Language="C#" %>
<%# Import Namespace="System.Data.Odbc" %>
<%
OdbcConnection oConn = new OdbcConnection("DSN=sailors");
oConn.Open();
if ((Request["MonsterNames"] != null) && (Request["Element"].ToString() != ""))
{
string str_sql = #"insert into MonsterList (MonsterNames,Element, Weakness) values " +
"('" + Request["MonsterNames"] + "'," +
"'" + Request["Element"] + "', '" + Request["Weakness"] + "')";
OdbcCommand oCmd = new OdbcCommand(str_sql, oConn);
oCmd.ExecuteNonQuery();
oCmd.Dispose();
oCmd = null;
Response.Write("<br><br><br>");
}
%>
<!DOCTYPE html>
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add Monster</title>
</head>
<body>
<div class="topnav" id="myTopnav">
<link rel="stylesheet" href="stylesheet.css" />
Home
Monster List
Search A Monster
</div>
<!-- all FORM elements (input, checkbox etc) contains data to submit. start of FORM -->
<form method="post" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<strong>Monster Name:</strong>
</td>
<td>
<asp:TextBox ID="MonsterNames" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<strong>It's Element:</strong>
</td>
<td>
<asp:TextBox ID="Element" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<tr>
<td>
<strong>Known Weaknesses (Seperate by '/'):</strong>
</td>
<td>
<asp:TextBox ID="Weakness" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnSubmit" runat="server" Text="Add Record" />
</td>
</tr>
</table>
</form>
</body>
</html>
<%
oConn.Close();
oConn.Dispose();
oConn = null;
%>
Working Display All Page
<%# Page Language="C#"%>
<%# Import Namespace="System.Data.Odbc" %>
<%
OdbcConnection oConn = new OdbcConnection("DSN=sailors");
oConn.Open();
string str_sql = "select * from MonsterList "; // this is an sql string '*' includes all fields from table
OdbcCommand oCmd = new OdbcCommand(str_sql, oConn);
OdbcDataReader oRs = oCmd.ExecuteReader();
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Monster List</title>
</head>
<body leftmargin="0" rightmargin="0" topmargin="0">
<div class="topnav" id="myTopnav">
<link rel="stylesheet" href="stylesheet.css" />
Home
Add Monster
Search A Monster
</div>
<table <link rel="displayrecordSS" href="displayrecordSS.css"/>
<%
while(oRs.Read())
{
string str_out = #"<tr valign=""top"">" +
"<td>" + oRs["MonsterNames"] + "</td>" +
"<td>" + oRs["Element"] + "</td>" +
"<td>" + oRs["Weakness"] + "</td>" +
"</tr>" +
#"<tr bgcolor=""#ff0000""><td height=""1"" colspan=""3""></td></tr>";
Response.Write(str_out);
}
%>
</table>
</body>
</html>
<%
oRs.Close();
oRs = null;
oCmd.Dispose();
oCmd = null;
oConn.Close();
oConn.Dispose();
oConn = null;
%>
I am trying to insert data from ASP.NET into a local SQL Server database. I am following from https://www.youtube.com/watch?v=8bNCfUaJPf8. maybe you can try to watch the video first. I am following exactly same for the process.
Here is the 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">
<title></title>
<style type="text/css">
.auto-style1 {
text-align: center;
}
.auto-style2 {
width: 100%;
}
.auto-style3 {
width: 183px;
}
.auto-style4 {
width: 183px;
height: 21px;
}
.auto-style5 {
height: 21px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 class="auto-style1">insert data</h2>
<br />
</div>
<table class="auto-style2">
<tr>
<td class="auto-style4">FirstName :</td>
<td class="auto-style5">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">LastName :</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">City :</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3"> </td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
</td>
</tr>
</table>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" OnSelecting="SqlDataSource1_Selecting" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
</form>
</body>
</html>
Here is the code-behind file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Table (fname, lname, city) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
}
When I am trying to insert the data, this error appears:
Table
is a SQL keyword, you should be able to use
[Table]
to distinguish your Table name from the keyword.
So try using
SqlCommand cmd = new SqlCommand("insert into [Table] (fname, lname, city) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
It's possible your textbox input contains a value that is escaping your string. The method you're using is open to sql injection attacks.
For example:
If textbox1.txt contains a ' character, it would break the query, because it would eacape the value.
You'd likely be able to see this if you look at the command text property of the SqlCommand object. I'd highly recommend you take a look at that property, and do some googling about sql injection. If your input on any of those boxes were " '; drop database; --", your whole database would be deleted.
This is likely an issue of your input not being sanitized or passed to sql correctly.
Folks,
Need one help in creating the dynamic controls in C#.
Like, I am putting ID, Text and all the mandatory validation properties into the database and from that values I need to create a control in ASP WinForm or Web page.
Please suggest me the view part to achieve the same.
here is my database table template
CREATE TABLE CONTROL(
PK_CONTROL_ID VARCHAR(128) NOT NULL,
CONTROL_NAME VARCHAR(128) NOT NULL,
PRIMARY KEY(CONTROL_ID)
);
CREATE TABLE CONTROLPROPERTY(
PK_PROPERTY_ID INT NOT NULL IDENTITY(1,1),
FK_CONTROL_ID INT NOT NULL FOREIGN KEY REFERENCES CONTROLPROPERTY(PK_CONTROL_ID),
CONTROLPROPERTY VARCHAR(128) NOT NULL,
CONTROLVALUES VARCHAR(128) NOT NULL,
PRIMARY KEY(PK_PROP_VALUE_ID)
);
**Example**
PK_CONTROL_ID CONTROL_NAME
1 TextBox
PK_PROPERTY_ID FK_CONTROL_ID CONTROLPROPERTY CONTROLVALUES
1 1 ID txtName
2 1 Visible true
3 1 ToolTip Name
Refered this example but I need to implement same table structure for the different types of controllers
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="TestControlFirst.index" %>
<%# Import Namespace="System.Data" %>
<!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)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Firstname");
dt.Columns.Add("Lastname");
for (int i = 0; i < 10; i++)
{
DataRow row = dt.NewRow();
row.ItemArray = new object[] {i,"Joe_"+i.ToString(),"Blow" +i.ToString()};
dt.Rows.Add(row);
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
}
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int rowid = (e.Item.ItemIndex);
TextBox tb = (TextBox)Repeater1.Items[rowid].FindControl("txtOne");
Label2.Text = tb.Text;
}
</script>
ASPX page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Repeater Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
<HeaderTemplate>
<table border="1" width="50%">
<tr>
<th>SELECT</th>
<th>ID</th>
<th>FIRST</th>
<th>LAST</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Button ID="btnOne" runat="server" Text="SELECT" /></td>
<td> <asp:TextBox ID="txtOne" runat="server" Text='<%# Eval("ID") %>' /></td>
<td><%# Eval("Firstname") %></td>
<td><%# Eval("LastName") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
<asp:Label ID="Label2" runat="server"></asp:Label>
</form>
</body>
</html>
Thanks in advance
Your best bet is to create dynamic Controls and add them to a PlaceHolder by looping the database rows and create Controls based on the row values. This needs to happen every time the page is loaded, and that includes a PostBack
while (reader.Read())
{
string controlType = reader["CONTROL_NAME"].ToString();
if (controlType == "TextBox")
{
TextBox textbox = new TextBox();
textbox.ID = reader["ID"].ToString();
textbox.Visible = Convert.ToBoolean(reader["Visible"]);
textbox.ToolTip = reader["ToolTip"].ToString();
PlaceHolder1.Controls.Add(textbox);
}
else if (controlType == "Label")
{
Label label = new Label();
label.ID = reader["ID"].ToString();
label.Visible = Convert.ToBoolean(reader["Visible"]);
label.Text = reader["Text"].ToString();
PlaceHolder1.Controls.Add(label);
}
else if (controlType == "Button")
{
//etc
}
}
And to read the form values on submit you basically need to do the same. Loop all the ID's and Control types from the database, create them dynamically and read their values.
As you can see this process can become complex real fast if you have a lot of different controls and rows, so think about your approach and see if this is the best solution.
Good morning .
I search many times before posting here .
I am working on a project like a survey [Questions and Answers]
I am able to get all questions in datalist , now i am searching a way to display the answers in Radio button list inside each question .
here is page load
protected void Page_Load(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["TMConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
//Getting All Questions
SqlDataAdapter dr = new SqlDataAdapter("select * from Question ", con);
DataSet ds = new DataSet();
dr.Fill(ds, "Qs");
OuterDataList.DataSource = ds.Tables["Qs"];
OuterDataList.DataBind();
}
here is page body
<body>
<form id="form1" runat="server">
<h1>Test Page</h1>
<asp:DataList ID="OuterDataList" RunAt="server">
<ItemTemplate>
<h4><%# DataBinder.Eval (Container.DataItem, "Question") %></h4>
<asp:RadioButtonList ID="RadioButtonList1" runat="server"></asp:RadioButtonList>
</ItemTemplate>
</asp:DataList>
</form>
i dont know how to bind radiobuttonlist and group the answers .
note : the common column between Question table and Answer table is Question_id
Firt will make a template like below.
<asp:DataList runat="server" ID="DataList1" RepeatDirection="Vertical"
DataKeyField="QuestionID" onitemdatabound="DataList1_ItemDataBound">
<ItemTemplate>
<table>
<tr>
<td>
<%# Eval("Question") %>
</td>
</tr>
<tr>
<td>
<asp:RadioButtonList runat="server" ID="RadioButtonList1">
</asp:RadioButtonList>
</td>
</tr>
</table>
</ItemTemplate>
After that using DataList1_ItemDataBound you can bind your answers.
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
RadioButtonList RadioButtonList1 = (RadioButtonList)e.Item.FindControl("RadioButtonList1");
//Get questionID here
int QuestionID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "QuestionID"));
//pass Question ID to your DB and get all available options for the question
//Bind the RadiobUttonList here
}
}
What I want to do is take all of the selected items from a milti-select listbox and put them in a comma separated string, so I can store it in a table. I've searched and found code, but for some reason the qualifier is never found to be "true". It sees every selected item as "false". Am I processing this in the wrong order?
Here's my ASP section (cut because it's a HUGE file, but this is the important stuff):
<%# Page Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PBR.WebForm1" MaintainScrollPositionOnPostback="true"%>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AJAXControls" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<link rel="stylesheet" href="Styles/ui.all.css" type="text/css" media="screen" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server" >
<asp:ScriptManager ID="ScriptManager2" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanelX" runat="server" UpdateMode="Conditional" Height="390px"
Width="900px" BorderStyle="Groove" BorderWidth="2px">
<ContentTemplate>
<AJAXControls:TabContainer runat="server" ID="tabContainer" Height="373" Width="900" >
<AJAXControls:TabPanel ID="secondTab" HeaderText="Tracking Page 2" runat="server">
<ContentTemplate>
<div style="border:1px solid blue;">
<asp:Panel ID="Panel2" runat="server" Height="40px" style="margin-left: 19px"
Width="860px">
<table>
<tr>
<td width="170">System/Document Change:</td>
<td width="30"><asp:ListBox id="ddlSysDocChg" runat="server" Width="90px" Rows="2" SelectionMode="Multiple"></asp:ListBox></td>
<td width="40"></td>
<td width="200">System/Document Change Completed:</td>
<td width="20"><asp:CheckBox ID="chkSysDocChg" runat="server" Text=" " AutoPostBack="true" /></td>
</tr>
</table>
</asp:Panel>
</div>
<p></p>
<div>
</div>
</ContentTemplate>
</AJAXControls:TabPanel>
</AJAXControls:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_OnClick"
runat="server" />
</div>
</asp:Content>
In my code-behind, I have this (as you can see, I've tried it 2 different ways and I believe I found both methods on this very website):
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
// Read the selected items from the listbox
//string SQLCode = "";
var selectedQuery = ddlSysDocChg.Items.Cast<ListItem>().Where(item => item.Selected);
string SQLCode = String.Join(",", selectedQuery).TrimEnd();
//foreach (ListItem listitem in ddlSysDocChg.Items)
// {
// if (listitem.Selected == true)
// {
// SQLCode = SQLCode + ", " + listitem;
// }
// }
}
Can anyone tell me why it always tells me there's nothing selected?
EDIT:
This is what's in my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(str))
// Check to see which tabs should be active
LoadTabPages();
{
try
{
string strSQL = "SELECT ComboValue, ComboText FROM dbo.tblComboBoxes WHERE ComboName = 'ddlSysDocChg' ORDER BY ComboText ASC;";
SqlDataAdapter adapter = new SqlDataAdapter(strSQL, str);
DataSet DailyRun = new DataSet();
adapter.Fill(DailyRun);
ddlSysDocChg.DataSource = DailyRun;
ddlSysDocChg.DataTextField = "ComboText";
ddlSysDocChg.DataValueField = "ComboValue";
ddlSysDocChg.DataBind();
foreach (ListItem item in ddlSysDocChg.Items)
{
item.Attributes.Add("Title", item.Text);
}
// Insert a blank row into the DropDownLists so there is no default name
ddlSysDocChg.Items.Insert(0, new ListItem("", ""));
}
catch (Exception ex)
{
// Handle the error
Console.WriteLine("Making Call to " + ex + "");
}
}
}
I think it's because your list is in an updatepanel whose postback is 'Conditional', and the button is 'outside' the updatepanel.
Try putting it 'inside' the update panel as in this tutorial:
http://msdn.microsoft.com/en-us/library/Bb399001(v=VS.100).aspx
Or alternatively, specify the button as a 'Trigger' as in the same tutorial.
Do you databind the ListBox also postbacks? Check the IsPostBack property:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack) DataBindListBox();
}