I have made search box using textbox and button control to search the data in my GridView, for datasource I'm using ObjectDataSource. In ObjectDataSource Class I'm Using parameterized procedure to select data from database table, but the problem was occured here, ObjectDataSource expect a value for parameter class. I have solved this with hardcoded the class if it null give the parameter value equals to white space, it works good.
If there is another way solve this without hardcoded the class, any answers would be helpful, thanks
Here is my ObjectDataSource Select Class
public static List<T_Penerbit> GetSearchPenerbit(string Cari)
{
if (string.IsNullOrWhiteSpace(Cari))
{
Cari = " ";
}
List<T_Penerbit> listSearchPenerbit = new List<T_Penerbit>();
string cs = ConfigurationManager.ConnectionStrings["cs_perpustakaan"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetPenerbitBySearch", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramSearch = new SqlParameter("#parameter", Cari);
cmd.Parameters.Add(paramSearch);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
T_Penerbit penerbit = new T_Penerbit();
penerbit.ID = Convert.ToInt32(rdr["ID"]);
penerbit.Penerbit = rdr["Nama_Penerbit"].ToString();
penerbit.Kota = rdr["Kota"].ToString();
penerbit.Handphone = rdr["Handphone"].ToString();
penerbit.Email = rdr["Email"].ToString();
listSearchPenerbit.Add(penerbit);
}
}
return listSearchPenerbit;
}
And here is my button Search Click event
protected void ButtonKelolaDataPenerbitCariPenerbit_Click(object sender, EventArgs e)
{
ObjectDataSourceCariDataPenerbit.SelectParameters.Clear();
ObjectDataSourceCariDataPenerbit.SelectParameters.Add("Cari", TextBoxKelolaDataPenerbitCariPenerbit.Text);
ObjectDataSourceCariDataPenerbit.DataBind();
}
Presentation changes :
<div style="margin-top:50px">
SEARCHING
<br /><br />
Enter Id : -
<asp:TextBox ID="txtSearchId" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</div>
Back-end updates :
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["StudDBConnectionString"].ToString());
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "select * from tbl_stud where id="+txtSearchId.Text;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
grvStudentWithoutDatasource.DataSource = dataTable;
grvStudentWithoutDatasource.DataBind();
}
Note: The given code is according to my database, Please change database column accordingly.
try this
aspx file:
<asp:ObjectDataSource runat="server" ID=" ObjectDataSourceCariDataPenerbit" TypeName="Penerbit" SelectMethod="GetSearchPenerbit">
<SelectParameters>
<asp:ControlParameter ControlID="TextBoxKelolaDataPenerbitCariPenerbit" Name="Cari" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
button Search Click event
protected void ButtonKelolaDataPenerbitCariPenerbit_Click(object sender, EventArgs e)
{
ObjectDataSourceCariDataPenerbit.DataBind();
}
Related
I want to create 3 Dropdown List for (Country, City and State) Cascading on Selection for The First Dropdown list Changing The Second and Selection for the second Changing The Third with SQL Server (ADO.Net) and ASP.Net C#!
and this error showing me
Can any one solve this error Please ?
Here the asp.net design code The Fist one..enter image description here
<asp:DropDownList ID="ddlFirst" runat="server" AutoPostBack="True" AppendDataBoundItems="True"
onselectedindexchanged="ddlFirst_SelectedIndexChanged">
<asp:ListItem Value="0">--Select Location--</asp:ListItem>
</asp:DropDownList>
The Second one:
<asp:DropDownList ID="ddlSecond" runat="server" AppendDataBoundItems="true" DataTextField="City"
DataValueField="City" AutoPostBack="True"
onselectedindexchanged="ddlSecond_SelectedIndexChanged">
<asp:ListItem Value="0">-- Select City--</asp:ListItem>
</asp:DropDownList>
And The Third..
<asp:DropDownList ID="ddlThird" runat="server" AppendDataBoundItems="true" DataTextField="State"
DataValueField="State">
<asp:ListItem Value="0">-- Select Area--</asp:ListItem>
</asp:DropDownList>
, the code of page load..enter image description here
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
txtid.Text = (pr.Project.OrderByDescending(b => b.ProID).FirstOrDefault().ProID
+1).ToString();
}
catch
{
txtid.Text = "1";
}
btnadd.Visible = true;
btndelete.Visible = false;
btnupdate.Visible = false;
GridView1.DataSource = pr.Project.ToList();
GridView1.DataBind();
}
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(#"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\GROUP.mdf;Integrated Security=True;User
Instance=True");
SqlCommand cmd = new SqlCommand("select * from Project", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddlFirst.DataSource = dt;
ddlFirst.DataBind();
}
}
, code of dropdown lists with c#..enter image description here
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ddlSecond.Items.Clear();
ddlSecond.Items.Add("Select State");
SqlConnection con = new SqlConnection(#"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\GROUP.mdf;Integrated Security=True;User
Instance=True");
SqlCommand cmd = new SqlCommand("select [City] from Project where Location=" +
ddlFirst.SelectedItem.Value, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddlSecond.DataSource = dt;
ddlSecond.DataBind();
}
protected void ddlSecond_SelectedIndexChanged(object sender, EventArgs e)
{
ddlSecond.Items.Clear();
ddlSecond.Items.Add("Select State");
SqlConnection con = new SqlConnection(#"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\GROUP.mdf;Integrated Security=True;User
Instance=True");
SqlCommand cmd = new SqlCommand("select [State] from Project where City=" +
ddlSecond.SelectedItem.Value, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddlSecond.DataSource = dt;
ddlSecond.DataBind();
}
and < The Error >..enter image description here
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request.
Please review the following specific error details and modify your source code appropriately.
Compiler Error Message:
CS1061: 'ASP.webusercontrol_project_wuc_ascx' does not contain a definition for 'ddlFirst_SelectedIndexChanged' and no extension method 'ddlFirst_SelectedIndexChanged' accepting a first argument of type 'ASP.webusercontrol_project_wuc_ascx' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 94:
Line 95:
Line 96: <asp:DropDownList ID="ddlFirst" runat="server" AutoPostBack="True" AppendDataBoundItems="True"
Line 97: onselectedindexchanged="ddlFirst_SelectedIndexChanged">
Line 98: <asp:ListItem Value="0">--Select Location--</asp:ListItem>
Source File: g:\Projects\Admin-WebApp-Final-Version\WebUserControl\Project-WUC.ascx Line: 96
I tried to create it with javascript only and it didn't work, and I tried to create it without a database and it didn't work
The error message...
CS1061: 'ASP.webusercontrol_project_wuc_ascx' does not contain a definition for 'ddlFirst_SelectedIndexChanged' and no extension method 'ddlFirst_SelectedIndexChanged' accepting a first argument of type 'ASP.webusercontrol_project_wuc_ascx' could be found (are you missing a using directive or an assembly reference?)
... is a slightly long-winded way of telling you that you're trying to call a method called ddlFirst_SelectedIndexChanged but the compiler couldn't find a method which meets that description.
From the name of the method that the compiler is looking for, I guess it's probably intended to be an event handler for the user changing the selection in the first drop-down list, so let's check that...
<asp:DropDownList ID="ddlFirst" runat="server" AutoPostBack="True" AppendDataBoundItems="True"
onselectedindexchanged="ddlFirst_SelectedIndexChanged">
<asp:ListItem Value="0">--Select Location--</asp:ListItem>
</asp:DropDownList>
Yep, this is what is causing the compiler to look for a method with that name, so let's see what the event handler method is actually called.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
And there's the answer - the event handler is called DropDownList1_SelectedIndexChanged, not ddlFirst_SelectedIndexChanged. Renaming the method to ddlFirst_SelectedIndexChanged should make the compiler error go away.
As an aside, concatenating user input into a SQL statement like this...
SqlCommand cmd = new SqlCommand("select [City] from Project where Location=" +
ddlFirst.SelectedItem.Value, con);
... isn't a great idea, because it's vulnerable to SQL injection attacks, which a malicious user could use to do serious damage to your database. Using stored procedures, or an object relational mapper such as Entity Framework, is a much safer way of implementing your data access.
If you use parameter's, you find this code quite a bit easier.
Say this markup:
<div style="float:left">
<h4>Region</h4>
<asp:DropDownList ID="cboRegion" runat="server"
DataTextField="Region"
AutoPostBack="true"
OnSelectedIndexChanged="cboRegion_SelectedIndexChanged" >
</asp:DropDownList>
</div>
<div style="float:left;margin-left:25px">
<h4>Country</h4>
<asp:DropDownList ID="cboCountry" runat="server" Width="250px"
DataTextField="Country"
AutoPostBack="true"
OnSelectedIndexChanged="cboCountry_SelectedIndexChanged" >
</asp:DropDownList>
</div>
<div style="float:left;margin-left:25px">
<h4>State</h4>
<asp:DropDownList ID="cboState" runat="server" Width="200px"
DataTextField="state"
AutoPostBack="true"
OnSelectedIndexChanged="cboState_SelectedIndexChanged" >
</asp:DropDownList>
</div>
<div style="float:left;margin-left:25px">
<h4>City</h4>
<asp:DropDownList ID="cboCity" runat="server" Width="220"
DataTextField="city"
dataValueField="ID"
AutoPostBack="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged" >
</asp:DropDownList>
</div>
Note how I "avoided" using the item list in the drop down boxes. The reason is if you re-fill, then you will have difficulty in clearing out the drop boxes.
And now our code is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
// load up first cbo box, region
SqlCommand cmdSQL =
new SqlCommand("SELECT region from vRegion ORDER BY region");
cboRegion.DataSource = MyRstP(cmdSQL);
cboRegion.DataBind();
cboRegion.Items.Insert(0, new ListItem("Select Region", ""));
}
protected void cboRegion_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboRegion.SelectedIndex > 0)
{
string strSQL =
#"SELECT Country FROM vCountryRegion
WHERE region = #region
ORDER BY Country";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#region", SqlDbType.NVarChar).Value = cboRegion.Text;
cboCountry.DataSource = MyRstP(cmdSQL);
cboCountry.DataBind();
cboCountry.Items.Insert(0, new ListItem("Select Country", ""));
}
}
protected void cboCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCountry.SelectedIndex > 0)
{
string strSQL =
#"SELECT state from vCountryStates
WHERE Country = #Country
ORDER BY state";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#Country", SqlDbType.NVarChar).Value = cboCountry.Text;
cboState.DataSource = MyRstP(cmdSQL);
cboState.DataBind();
cboState.Items.Insert(0, new ListItem("Select State", ""));
}
}
protected void cboState_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboState.SelectedIndex > 0)
{
string strSQL =
#"SELECT id, city from vCities
WHERE Country_name = #Country
AND state_name = #State
ORDER BY city";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#Country", SqlDbType.NVarChar).Value = cboCountry.Text;
cmdSQL.Parameters.Add("#State", SqlDbType.NVarChar).Value = cboState.Text;
cboCity.DataSource = MyRstP(cmdSQL);
cboCity.DataBind();
cboCity.Items.Insert(0, new ListItem("Select City", ""));
}
}
And the result is now this:
And in the above, I also had this little routine (no need to type over and over the code to build a connection and load the data).
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Countries))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
I have a method that i would like to use multiple times, that basically populates a Dropdown List.
public void PopulateDropdown(string selectedValue, object listname)
{
String connString = ConfigurationManager.ConnectionStrings["MySql"].ToString(); //Conn string
MySqlConnection mySqlConnection = new MySqlConnection(connString); //Objekt
MySqlCommand cmd = new MySqlCommand(); //cmd objekt
cmd.CommandText = "SELECT NAME FROM CustomerDb WHERE CITY = \"" + selectedValue + "\"";
cmd.CommandType = CommandType.Text;
cmd.Connection = mySqlConnection;
DropDownList dropDownList = listname as DropDownList;
mySqlConnection.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "NAME";
dropDownList.DataBind();
mySqlConnection.Close();
}
My call looks like this:
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
string value = DropDownList3.SelectedValue;
PopulateDropdown(value, DropDownList4);
}
I know that my call and my method is correct, but for some reason, im not able to call it in DropDownList3_SelectedIndexChanged.
When i select a value in DropDownList3 it just reloads and picks the default value "Select city".
<asp:DropDownList ID="DropDownList3" CssClass="btn btn-default btn-md pull-right" runat="server" OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>Select city</asp:ListItem>
<asp:ListItem>City1</asp:ListItem>
<asp:ListItem>City2</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList4" runat="server" CssClass="btn btn-default btn-md pull-right" OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged" AutoPostBack="true" Style="">
</asp:DropDownList>
my DropDownList3_SelectedIndexChanged looks like this:
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
string value = DropDownList3.SelectedValue;
PopulateDropdown(value, DropDownList4);
}
The postback doesn't reach breakpoint in method.
Well I don't really know if this will answer your question, but when getting a value from the database and using those data to fill a combobox or dropdownlist, I use this code/query:
String path = "Data Source = LOCALHOST; Initial Catalog= sample_database; username='root'; password=''";
MySqlConnection sqlcon = new MySqlConnection(path);
MySqlCommand sqlcom = new MySqlCommand();
MySqlDataReader sqlread;
sqlcon.Open();
sqlcom.CommandType = CommandType.Text;
sqlcom.CommandText = "SELECT name from database_table where city = '"+TextBox1.text+"'";
sqlcom.Connection = sqlcon;
sqlread = sqlcom.ExecuteReader();
while (sqlread.Read()) //use loop to get all data in the specified column
comboBox1.Items.Add(sqlread[0].ToString()); //place the data gathered in the combobox or dropdownlist
sqlcon.Close();
It could be that you're populating the City list on page load, and the AutoPostBack reloads the list. See DropDownList's SelectedIndexChanged event not firing
Im having a problem with a dropdownlist in asp.net.
When i try to get the selected value of the list it doesnt return anything.
The aspx looks like this
<div class="form-signin">
<h2 class="form-signin-heading">Slet besked</h2>
<div class="input-group">
<span class="input-group-addon">ID</span>
<asp:dropDownList runat="server" CssClass="form-control" ID="sletBox" />
</div>
<asp:Button runat="server" CssClass="btn btn-lg btn-block btn-danger" Text="Slet" OnClick="Slet" />
</div>
And the kode behind it looks like this
protected void Slet(object sender, EventArgs e)
{
Response.Write("wow der sker noget");
Response.Write(sletBox.SelectedItem.Value);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection myconnection = new SqlConnection();
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder();
myconnection.ConnectionString = constr;
myconnection.Open();
string sqlcmd = "DELETE FROM messages WHERE messageid = '" + sletBox.SelectedValue.ToString() + "'";
SqlCommand messageDelete = new SqlCommand(sqlcmd, myconnection);
messageDelete.ExecuteNonQuery();
myconnection.Close();
}
The only thing that works is the response.write(wow) not the selectedvalue
EDIT:
The page_load code
protected void Page_Load(object sender, EventArgs e)
{
DataTable subjects = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}
You're doing the databinding for the dropdownlist in the pageload and not checking for IsPostBack. As a result when the button triggers the clik it resets the selectedvalue. Change you PageLoad like below
if (!IsPostBack)
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}
As a side note as Mathew suggested try adding using to better manage your connections objects so it's properly disposed after it's been used.
You must load your DropDownList data only if IsPostBack is false, otherwise you'll be reloading the control every postback. Once the data bound to the control is changed, the selected value is lost as well. Keep in mind that the Page_Load event is fired when the SelectedIndexChanged event occurs.
if(!Page.IsPostBack)
{
DataTable subjects = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am not able to recognize what I am doing wrong in my code. Can someone help ? I want to delete all the images which are checked using c# .
my code snippet looks like this :-
SqlConnection con = new
SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
SqlDataAdapter adap;
DataSet ds;
string Query;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
protected void binddata()
{
string str = "select * from photos";
SqlCommand cmd = new SqlCommand(str, con);
adap = new SqlDataAdapter(str, con);
ds = new DataSet();
adap.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
con.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)
Repeater1.Items[i].FindControl("CheckBox1");
if (((CheckBox)Repeater1.Items[i].FindControl("CheckBox1")).Checked)
{
//This assumes data type of messageID is integer, change (int) to the right type
CheckBox CheckBox = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1");
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("literal1");
string Id = litMessageId.Text;
mySQL = string.Format("delete from photos where id = '{0}'", Id);
SqlCommand cmdDelete = new SqlCommand(mySQL, con);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
}
catch
{
Label2.Text = "errror";
}
}
.aspx page contains :-
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<img src='images/<%#DataBinder.Eval(Container.DataItem,"images") %>' height="150" width="150" alt="" border="0" />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</br>
</ItemTemplate>
</asp:Repeater>
Thanks in advance :)
Here are some pointers:
The names you use are difficult to understand in your codebehind. You now have 1 repeater but in case you have multiple it is better to use a more specific name.
Depending on the .NET version you can use generic types to declare your variables.
SqlCommand cmd = new SqlCommand(str, con);
becomes:
var sqlCommand = new SqlCommand(queryString, connectionString);
Your not closing the connection. If your in newer versions of .NET the best approach would in my opinion be:
private string ConnectionString = webConfigurationManager.ConnectionStrings["connectionstring"] != null ? WebConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString : "";
if (!string.IsNullOrEmpty(this.ConnectionString))
{
using (var sqlConnection = new SqlConnection(this.ConnectionString))
{
//your code here
}
}
You are catching an error but your not doing anything with the provided information.
use:
Catch (Exception exception)
{
ErrorLabel.Text = string.format("The following error has occurred: {0}.", exception.Message);
}
to use the exception.Message where desired.
In modern implementations you are most probably better off using an MVC application using EntityFramework and MVC Razor.
Defining your SQL queries like that is dangerous also. If I edit the post value of the literal to something like "ID AND 1 = 1" I will now delete all photos.
Here are some pages to help you get started with Entityframework and MVC:
http://www.asp.net/mvc/tutorials
http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B
I will give you some good pointers in improvements in a minute. First try this and change the literal value to the column you use as an id in case I got it wrong:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<img src='images/<%#DataBinder.Eval(Container.DataItem,"images") %>' height="150" width="150" alt="" border="0" />
<asp:Literal ID="Literal1" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"id") %>'></asp:Literal>
</br>
</ItemTemplate>
</asp:Repeater>
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
SqlDataAdapter adap;
DataSet ds;
string Query;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
protected void binddata()
{
string str = "select * from photos";
SqlCommand cmd = new SqlCommand(str, con);
adap = new SqlDataAdapter(str, con);
ds = new DataSet();
adap.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
con.Open();
String mySQL;
try
{
for (int i = 0; i < Repeater1.Items.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)Repeater1.Items[i].FindControl("CheckBox1")
Literal litMessageId = (Literal)Repeater1.Items[i].FindControl("literal1");
if (CheckBox1 != null && litMessageId != null && CheckBox1.Checked)
{
string Id = litMessageId.Text;
mySQL = string.Format("delete from photos where id = '{0}'", Id);
SqlCommand cmdDelete = new SqlCommand(mySQL, con);
cmdDelete.ExecuteNonQuery();
// Continue your code here
}
else
{
}
}
}
catch
{
Label2.Text = "error";
}
}
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).