I have a code like this
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Visible="False" Text="Please update the price"></asp:Label>
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
and C# is
namespace WebApplication6
{
public partial class WebForm20 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["onealbumid"] != null)
{
Label1.Visible = true;
int onealbumid = Convert.ToInt32(Session["onealbumid"]);
String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);
SqlCommand cmd = new SqlCommand("Select Price from OneAlbum where OneALbumID='" + onealbumid + "'", con);
con.Open();
TextBox1.Text = cmd.ExecuteScalar().ToString();
con.Close();
}
else {
Response.Redirect("~/BENEinsertOneAlbum3.aspx");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
String Artists = System.Configuration.ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Artists);
int onealbumid = Convert.ToInt32(Session["onealbumid"]);
SqlCommand command = new SqlCommand(#"UPDATE [dbo].[OneAlbum]
SET Price=#Price where OneAlbumID =" + onealbumid + ";", con);
command.Parameters.AddWithValue("#Price", TextBox1.Text);
con.Open();
command.ExecuteNonQuery();
con.Close();
Response.Redirect("~/BENEinsertOneAlbum3.aspx");
}
}
}
There is a page/form, before this page, users select the price which users want to change from the gridview
I want users to edit new "Price" in the textbox1 on this page.
So this is happening right now.
For example, I choose "Price" 22 before this page and when this page opens/loads textbox1 showing 22.
so I change/type to 40 in Texbox1, and click button.
The price is still 22. not 40 and I checked the database, which still did not change, still 22
why is this happening?
The Page_Load will overwrite the data you are entering. Put a !IsPostBack check around that so that when you do click the button the data isn't being put back to what it was when the form loaded.
Also, where is a gridview in this code? There is such a class and thus beware of what terms you use given the code you show.
Related
I have created two individual form and store data in one table but problem is that data store individually row ? I want to store data in one row.
and then i created two individual form and store data in one table and my data is store individually row that is issue?
table name: manager
Database fieldname:
- managerid int pk autoincrement
- firstname varchar(50)
- lastname varchar(50)
- address varchar(50)
- permanantaddress varchar(50)
- mno int
- experiance int
- currentcompanyname varchar(50)
- previouscompanyname varchar(50)
- currentsalary int
- expectedsalary int
Registrationform.aspx
<div>
FirstName: <asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
<br />
lastName: <asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Insert" OnClick="Button1_Click" />
</div>
Registrationform.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string query = "Insert into manager (firstname,lastname) values(#firstname,#lastname)SELECT SCOPE_IDENTITY()";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#firstname", txtfname.Text);
cmd.Parameters.AddWithValue("#lastname",txtlname.Text);
cn.Open();
int? primaryKey = Convert.ToInt32(cmd.ExecuteScalar());
this.Session["primaryKey"] = primaryKey;
if(primaryKey != null)
{
Response.Redirect("Contactus.aspx");
}
cmd.ExecuteNonQuery();
cn.Close();
}
Contactus.aspx
Address:
<asp:TextBox ID="txtadd" runat="server"></asp:TextBox>
<br />
PermanantAddress:
<asp:TextBox ID="txtperaddress" runat="server"></asp:TextBox>
<br />
Mno:
<asp:TextBox ID="txtmno" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Insert" OnClick="Button1_Click" />
Contactus.aspx.cs
string sessionvariable;
protected void Page_Load(object sender, EventArgs e)
{
sessionvariable = Session["primaryKey"].ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
string query = "update manager set address=#address,permanantaddress=#permanantaddress,mno=#mno where managerid=#managerid";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#address", txtadd.Text);
cmd.Parameters.AddWithValue("#permanantaddress", txtperaddress.Text);
cmd.Parameters.AddWithValue("#mno", txtmno.Text);
cn.Open();
if (sessionvariable != null)
{
**here give an error System.Data.SqlClient.SqlException: Must declare the scalar variable "#managerid"**
cmd.ExecuteNonQuery();
}
cn.Close();
}
I want to store data in one row.
see my watch window Image:
my problem is that datastore in individually row that is my problem?
enter image description here
Give an Error: here give an error System.Data.SqlClient.SqlException: Must declare the scalar variable "#managerid"
try this
string sessionvariable;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
sessionvariable = Session["primaryKey"].ToString();
string query = "update manager set address=#address,permanantaddress=#permanantaddress,mno=#mno where managerid=#managerid";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#address", txtadd.Text);
cmd.Parameters.AddWithValue("#permanantaddress", txtperaddress.Text);
cmd.Parameters.AddWithValue("#mno", txtmno.Text);
cn.Open();
if (sessionvariable != null)
{
**here give an error System.Data.SqlClient.SqlException: Must declare the scalar variable "#managerid"**
cmd.ExecuteNonQuery();
}
cn.Close();
}
Read More
I am trying to user the select from one drop down list to filter another one, with update panels so it doesn't refresh the page. However, I cannot get it to work.
Here is the code below:
ASPX (This is below all JS content):
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
Module Code*
<asp:DropDownList ID="ModuleCodeDDL" AutoPostBack="true" OnSelectedIndexChanged="ModuleCodeDDL_SelectedIndexChanged" Style="width: 200px;" runat="server"></asp:DropDownList>
Module Name*
<asp:DropDownList ID="ModuleTitleDDL" AutoPostBack="true" Style="width: 250px;" runat="server"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
THE CODE BEHIND (C#):
//I INITIALLY POPULATE THE TWO DROP DOWN LISTS
connect.Open();
string moduleSql = "Select Module_Code, Module_Title from [newModule]";
SqlCommand moduleCommand = new SqlCommand(moduleSql, connect);
SqlDataReader modules = moduleCommand.ExecuteReader();
while (modules.Read())
{
string moduleCode = modules.GetString(0);
string moduleName = modules.GetString(1);
string module = moduleCode;
ModuleCodeDDL.Items.Add(module);
}
connect.Close();
connect.Open();
string moduleSql1 = "Select Module_Code, Module_Title from [newModule]";
SqlCommand moduleCommand1 = new SqlCommand(moduleSql1, connect);
SqlDataReader modules1 = moduleCommand1.ExecuteReader();
while (modules1.Read())
{
string moduleCode = modules1.GetString(0);
string moduleName = modules1.GetString(1);
string module = moduleName;
ModuleTitleDDL.Items.Add(module);
}
connect.Close();
}
//THIS IS THE FUNCTION THAT IS CALLED WITH THE ONSELECTEDINDEXCHANGED
protected void ModuleCodeDDL_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection(WebConfigurationManager.ConnectionStrings["ParkConnectionString"].ToString());
ModuleTitleDDL.Items.Clear();
connect.Open();
string moduleCode = ModuleCodeDDL.SelectedItem.Value;
string moduleTitleSQL = "Select Module_Code, Module_Title From [newModule] Where Module_Code ='" + moduleCode + "'";
SqlCommand moduleTitleNew = new SqlCommand(moduleTitleSQL, connect);
SqlDataReader newModuleTitle1 = moduleTitleNew.ExecuteReader();
ModuleTitleDDL.Items.Add("");
while (newModuleTitle1.Read())//Add the results to the dropdownlist
{
ModuleTitleDDL.Items.Add(newModuleTitle1.GetString(1).ToString());
}
connect.Close();
}
It works without Update Panels with a full post back, but I can't seem to get it to work with Update Panels.
If anyone could shed some light on how to fix this issue, it would be much appreciated.
Thanks in advance!
I am try to toggle the display subnet data(childList). This codes below are working fine, but not able to toogle the display. When I click on the (+) sign, the ChildList dataList expands and displays the list subset data (Contact). However, I want to change the (+) to (-) when childList data expanded. And when user clicks on (-), it will collapse back (the child list disappear)
Any idea how to do this? an example code would be great since I am a newbie of ASP.NET.
<table width="595px">
<asp:DataList BackColor="#ffffff" id="DataList1" DataSourceID="dsCompanyList" runat="server" Width="100%" DataKeyField="Company">
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="LinkButton1" runat="server" Text="+" CommandArgument='<%#Container.ItemIndex%>'
OnCommand="LinkButton1_Command"
></asp:LinkButton>
</td>
<td><%#Eval("Row")%></td>
<td><%#Eval("Company")%></td>
</tr>
<asp:Panel ID="pnlChildView" runat="server">
<asp:DataList ID="childList" runat="server" Width="100%">
<ItemTemplate>
<tr>
<td><%#Eval("FirstName")%></td>
<td><%#Eval("LastName")%></td>
</tr>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
</table>
Code Behind:
public partial class _CompanyList2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
//pass index of item in command argument
int itemIndex = Convert.ToInt32(e.CommandArgument);
//depending on your needs bind the details on demand
//or preload during ItemDataBound
Panel childViewPanel = (Panel)DataList1.Items[itemIndex].FindControl("pnlChildView");
if (childViewPanel != null)
{
//toggle visibility of childViewPanel and bind child list if panel is visible
DataList childList = (DataList)childViewPanel.FindControl("childList");
if (childList != null)
{
//int keyValue = (int)DataList1.DataKeys[itemIndex];
string keyValue = (string)DataList1.DataKeys[itemIndex];
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connApps"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT FirstName, LastName FROM dbo.Import_CompanyContact WHERE REPLACE(Company, '''', '') = '" + keyValue + "'", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader())
{
childList.DataSource = dr;
childList.DataBind();
}
}
}
}
}
}
}
I've created a search function with 3 DropDownLists and a search button. How will I display it on the same page?
Here's my code:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//read sql server connection string from web.config file
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
PROVINCE_CODE = '" + ddlProvince.SelectedValue + "'", conn);
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
PROVINCE_CODE = '" + ddlProvince.SelectedValue + "'", conn);
SqlCommand comm = new SqlCommand("SELECT * FROM emed_doctors_hospitals WHERE CITY_CODE =#ccode", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSched.DataSource = dt;
ddlSched.DataTextField = "SCHEDULE";
ddlSched.DataValueField = "HOSPITAL_CODE";
ddlSched.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
When someone selects a value in the DropDownList and hits the button, it will display the lists of doctors available in the province, city and per particular schedule.
Check this sample. I have used SQLDatasource with SelectParameters for this example (you
can replace it with your own object datasource, custom binding etc.) SQLDataSource Select Parameters
The second dropdownlist automatically populates when the first dropdownlist is changed
On Button even I am just selecting the currently selected values of each dropdownlist (You can select your doctor list in the same way)
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Cascading DropDown.aspx.cs"
Inherits="Cascading_DropDown" %>
<!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> </head> <body>
<form id="form1" runat="server">
<div>
<label>
Category:</label>
<asp:DropDownList ID="ddlCategories" runat="server" AppendDataBoundItems="True" AutoPostBack="True"
DataSourceID="sdsCategory" DataTextField="CategoryName" DataValueField="CategoryID"
OnSelectedIndexChanged="ddlCategories_SelectedIndexChanged">
<asp:ListItem Text="-Select-" Value="" />
</asp:DropDownList>
<br />
<label>
Products:</label>
<asp:DropDownList ID="ddlProducts" runat="server" DataSourceID="sdsProducts" DataTextField="ProductName"
DataValueField="ProductID">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Search Prodcut" OnClick="Button1_Click" />
<asp:Label ID="lblSelectedValues" runat="server"></asp:Label>
</div>
<asp:SqlDataSource ID="sdsCategory" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories] ORDER BY [CategoryName]">
</asp:SqlDataSource>
<asp:SqlDataSource ID="sdsProducts" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName] FROM [Alphabetical list of products] WHERE ([CategoryID] = #CategoryID)">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCategories" Name="CategoryID" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</form> </body> </html>
.CS
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCategories.SelectedValue == "")
{
ddlProducts.Items.Clear();
ddlProducts.SelectedIndex = -1;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
lblSelectedValues.Text = "You selected Category:" + ddlCategories.SelectedItem.Text + " & prodcut:" + ddlProducts.SelectedItem.Text;
}
You can drop a gridview on form like Abel said & on your button click event, fetch each drop down list selected value & execute your query & databaind your gridview like you are already doing with your drop down lists.
All you essentially need to do is to place the controls in the ASPX page declaratively:
<asp:DropDownList id="ddlSche" runat="server" />
You can calculate the results in the Page_Load using ddlSched.SelectedValue and similar methods.
Essentially, you use the button's onclick handler for this type of thing:. But since you already have a SelectedIndexChanged event, it seems that you're on the right track. It's fired when the user postbacks the page and the index was changed (or, in other words, the user selected something else than the current selection in the DropDownList).
How do I make an autocomplete TextBox in C# that binds to a data source?
You can use either jQuery Autocomplete or ASP.NET AJAX Toolkit Autocomplete
I use ajaxcontrol toolkit's AutoComplete
Try this:
.aspx page
<td>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"
CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</asp:AutoCompleteExtender>
Now To auto populate from database :
public static List<string> GetCompletionList(string prefixText, int count)
{
return AutoFillProducts(prefixText);
}
private static List<string> AutoFillProducts(string prefixText)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like #Search + '%'";
com.Parameters.AddWithValue("#Search", prefixText);
com.Connection = con;
con.Open();
List<string> countryNames = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
countryNames.Add(sdr["ProductName"].ToString());
}
}
con.Close();
return countryNames;
}
}
}
Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.
Create Procedure GetProductDet
(
#ProductName varchar(50)
)
as
begin
Select BrandName,warranty,Price from ProdcutMaster where ProductName=#ProductName
End
Create a function name to get product details ::
private void GetProductMasterDet(string ProductName)
{
connection();
com = new SqlCommand("GetProductDet", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ProductName", ProductName);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds=new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
//Binding TextBox From dataTable
txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();
txtwarranty.Text = dt.Rows[0]["warranty"].ToString();
txtPrice.Text = dt.Rows[0]["Price"].ToString();
}
Auto post back should be true
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
Now, Just call this function
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//calling method and Passing Values
GetProductMasterDet(TextBox1.Text);
}
1-Install AjaxControl Toolkit easily by Nugget
PM> Install-Package AjaxControlToolkit
2-then in markup
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="txtMovie"
runat="server" />
3- in code-behind : to get the suggestions
[System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey) {
// Create array of movies
string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};
// Return matching movies
return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();
}
source: http://www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx
aspx Page Coding
<form id="form1" runat="server">
<input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
required="">
<datalist id="datalist1" runat="server">
</datalist>
</form>
.cs Page Coding
protected void Page_Load(object sender, EventArgs e)
{
autocomplete();
}
protected void autocomplete()
{
Database p = new Database();
DataSet ds = new DataSet();
ds = p.sqlcall("select [name] from [stu_reg]");
int row = ds.Tables[0].Rows.Count;
string abc="";
for (int i = 0; i < row;i++ )
abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
datalist1.InnerHtml = abc;
}
Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.