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).
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 need to get products based on chosen subcategory. Now, it displays all products. How to do this? Here is my code. How to pass Subcategory.Id in button click?
...
<td>Subcategory</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="Id">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Id], [Name] FROM [SubCategory] WHERE ([IdCategory] = #IdCategory)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="IdCategory" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</td>
</tr>
...
protected void Button1_Click(object sender, EventArgs e)
{
...
SqlCommand command = new SqlCommand("SELECT productName, quantity, price FROM Product JOIN SubCategory ON Product.id_subcategory = SubCategory.id", _connection);
...
}
I'm gonna assume that the DropDownList2 control already contains the subcategory data.
You can get your subcategory ID in Button1_Click event with
DropDownList2.SelectedValue
Assuming that you have the following database table structure:
Product
- Id (PK)
- ProductName
- Quantity
- Price
- MainCatID (FK)
- SubCatID (FK)
- others...
Category
- Id (PK)
- Name
SubCategory
- Id (PK)
- Name
- IdCategory (FK)
Make sure to add the namespace System.Configuration so that you can access your connection string from your web.config file.
Instantiate an SqlConnection class to identify the database connection:
Create methods to display the list of categories and sub categories from their respective drop down list controls
Include an AutoPostBack property to DropDownList1 then set to true so that each time you select an item from the list, it will 'regenerate' a list of sub categories based from the selected category value.
Create an OnSelectedIndexChanged event of DropDownList1 calling the DisplaySubCategories() method.
Create a method that will display list of products based from selected category and sub category values
Include similar process from Step #4 to DropDownList2
Call the two methods inside the page load event.
SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayCategories();
DisplaySubCategories();
}
}
void DisplayCategories()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Id, Name FROM Category";
SqlDataReader data = cmd.ExecuteReader();
DropDownList1.DataSource = data;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();
con.Close();
}
void DisplaySubCategories(string ID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Id, Name FROM SubCategory WHERE IdCategory = #IdCategory";
cmd.Parameters.AddWithValue("#IdCategory", ID);
SqlDataReader data = cmd.ExecuteReader();
DropDownList2.DataSource = data;
DropDownList2.DataTextField = "Name";
DropDownList2.DataValueField = "Id";
DropDownList2.DataBind();
con.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DisplaySubCategories(DropDownList2.SelectedValue);
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DisplayProducts(DropDownList1.SelectedValue, DropDownList2.SelectedValue);
}
void DisplayProducts(string mainCatID, string subCatID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"SELECT productName, quantity, price FROM Product
WHERE MainCatID = #MainCatID AND SubCatID=#SubCatID";
cmd.Parameters.AddWithValue("#MainCatID", mainCatID);
cmd.Parameters.AddWithValue("#SubCatID", subCatID);
SqlDataReader data = cmd.ExecuteReader();
string result = string.Empty;
while (data.Read())
{
result += "Name = " + Convert.ToString(reader["productName"]) + "; ";
result += "Quantity = " + Convert.ToString(reader["quantity"]) + "; ";
result += "Price = " + Convert.ToString(reader["price"]);
result += "<br />";
}
ReadAllOutput.Text = result;
con.Close();
}
.aspx
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" />
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" />
I removed all the existing SqlDataSource controls because I find them messy.
Update:
You can also declare the method DisplayProducts() inside the Button click event
protected void Button1_Click(object sender, EventArgs e)
{
DisplayProducts(DropDownList1.SelectedValue, DropDownList2.SelectedValue);
}
PS: Some syntax might be incorrect (case-sensitivity) and I'm not using an IDE as of the moment.
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();
}
I am creating a web page that contains one Dropdownlist and Gridview.
Query is Dropdownlist will contains SQL Server database table list. When I select a table name from dropdownlist the Gridview needs to show entire table data and able to perform edit, update, delete, cancel action.
When I click edit Gridview need to show update and cancel buttons and it update should update dropdownlist table and also delete.
My code looks this:
Html page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DataGridView_Sample._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>
<style type="text/css">
.style1
{
font-weight: bold;
text-decoration: underline;
font-size: x-large;
text-align: center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h5 class="style1">
Data Grid View Sample</h5>
</div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="-- Select --" Value=""></asp:ListItem>
<asp:ListItem Text="Emp" Value="Emp"></asp:ListItem>
<asp:ListItem Text="Dept" Value="Dept"></asp:ListItem>
</asp:DropDownList>
<br />
<br />
<b>Grid View:</b>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" Height="181px"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
Width="518px">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
<EmptyDataTemplate>
</EmptyDataTemplate>
</asp:GridView>
</form>
</body>
</html>
.aspx page code:
namespace DataGridView_Sample
{
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=SHINY-PC\\SQLEXPRESS;Initial Catalog=NRK;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
con.Open();
cmd = new SqlCommand("Select name from sys.tables order by name", con);
da = new SqlDataAdapter(cmd);
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--Select--", "--Select--"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex != 0)
{
cmd = new SqlCommand("select * from " + DropDownList1.SelectedItem.Value, con);
con.Open();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
cmd = new SqlCommand("select * from " + DropDownList1.SelectedItem.Value, con);
con.Open();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.EditIndex = Convert.ToInt16(e.NewEditIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
}
}
Please any one can help.
Thanks in advance.
Given the above, I'd create a database table with two fields: tablename and columnname. There will be 4 rows with tablename = emp and each row will have a columnname = one of the columns from the emp table. Similarly, there will be 6 rows where tablename = dept and each row will have a columnname = one of the columns from the dept table. Then, in your GridView1_RowUpdating event, you can pull the names of the columns from the database based on the table that's been chosen in the DropDownList and update accordingly using whatever stored procedure you have in place for that table. In GridView1_RowCancelingEdit, you just need to do
GridView1.EditIndex = -1;
and rebind your data (you'll need a method for that) you're done.
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.