Can't JOIN tables in ASP.NET - c#

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.

Related

How do i load CheckBoxList from a Selected Value from DropDownList?

i'm trying to do a display database's item(tables, rows, fk,...).
I'm stucking at first few step. I loaded the db's names into a DropDownList. But i tried to load Tables from Selected db's name into CheckBoxList but it shows nothing.
Here are my codes
aspx:
<form id="form1" runat="server" method="get">
<div>
<asp:DropDownList ID="drpListDBName" runat="server" OnSelectedIndexChanged="drpListDBName_SelectedIndexChanged">
</asp:DropDownList>
</div>
<div>
<asp:CheckBoxList ID="chkListTable" runat="server">
</asp:CheckBoxList>
</div>
aspx.cs:
public static String dbname = "";
protected void Page_Load(object sender, EventArgs e)
{
String query = "SELECT * FROM SYS.sysdatabases WHERE name != 'master'" +
" and name != 'tempdb'" +
" and name != 'model'" +
" and name != 'msdb'" +
" and name != 'distribution'";
Program.Connect();
if(!Page.IsPostBack)
{
drpListDBName.DataSource = Program.ExecSqlDataReader(query);
drpListDBName.DataTextField = "name";
drpListDBName.DataBind();
}
}
protected void drpListDBName_SelectedIndexChanged(object sender, EventArgs e)
{
dbname = drpListDBName.SelectedValue.Trim();
String query = "USE " + dbname +
" SELECT * FROM SYS.tables" +
" WHERE is_ms_shipped = 0";
Program.Connect();
if (chkListTable.Items.Count > 0)
chkListTable.Items.Clear();
chkListTable.DataSource = Program.ExecSqlDataReader(query);
chkListTable.DataTextField = "name";
chkListTable.DataBind();
Response.Write(chkListTable);
}
I'm still new to asp.net. Thanks in advance.
Ok, while you could send your 2nd selection (the list of tables) to a check box list?
(and if you needing to select multiple tables - perhaps yes).
but, lets do one better. Lets use two combo boxes. First one, select database, fill 2nd combo box with tables.
Then you select a table, and display the table in a grid.
So, first up is (possbile) is the connection string used. We can assume that you built or setup at least one working connection string to one of the databases on that sql server.
So, project->"my project name settings".
You get this:
So, I have a few already made, but note the [...] button, if you click on that, then VS will launch a connection builder for you (nice and easy). And you can test the connection.
So, we just start out by using TEST4. (note that this DOES put the connection string automatic in web config for you).
Ok, So lets drop in a combo box (to select database).
And then our check box list.
So, we have this markup:
<h4>Select Database</h4>
<asp:DropDownList ID="DropDownList1" runat="server" Width="177px"
DataTextField="name"
DataValueFeild="name"
AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataTextField="TABLE_NAME"
DataValueField="TABLE_NAME" >
</asp:CheckBoxList>
And now we have this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
Session["MyCon"] = Properties.Settings.Default.TEST4;
string query = "SELECT * FROM SYS.sysdatabases WHERE name != 'master'" +
" and name != 'tempdb'" +
" and name != 'model'" +
" and name != 'msdb'" +
" and name != 'distribution' ORDER BY Name";
DropDownList1.DataSource = MyRst(query);
DropDownList1.DataBind();
}
public DataTable MyRst(string strSQL)
{
var rst = new DataTable();
using (SqlConnection conn = new SqlConnection((Session["MyCon"] as string)))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rst.Load(cmdSQL.ExecuteReader());
}
}
return rst;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// set connecting string from TEST4 to whatever database selected
string strCon = Session["MyCon"] as string;
string strDB = DropDownList1.SelectedItem.Value;
strCon = strCon.Replace("Initial Catalog = test4;", strDB);
Session["MyCon"] = strCon;
// now load check box list with all tables
string strSQL = #"SELECT TABLE_NAME FROM [" + strDB + "].INFORMATION_SCHEMA.TABLES " +
"WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME";
CheckBoxList1.DataSource = MyRst(strSQL);
CheckBoxList1.DataBind();
}
So, now we get this:
So, yes, you can set a datatable to check box list. But, some of my databases have quite a few tables - too long (many) check boxes.
So, lets change our code to two combo boxes.
However, we need a "please select" for the combo boxes.
So, our mark up is now this:
<h4>Select Database</h4>
<asp:DropDownList ID="DropDownList1" runat="server" Width="180px"
DataTextField="name"
DataValueFeild="name"
AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<h4>Select Table</h4>
<asp:DropDownList ID="DropDownList2" runat="server" Width="180"
DataTextField="TABLE_NAME"
DataValueField="TABLE_NAME"
AutoPostBack="true" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged"
>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" CssClass="table">
</asp:GridView>
Our code is now this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
Session["MyCon"] = Properties.Settings.Default.TEST4;
string query = "SELECT * FROM SYS.sysdatabases WHERE name != 'master'" +
" and name != 'tempdb'" +
" and name != 'model'" +
" and name != 'msdb'" +
" and name != 'distribution' ORDER BY Name";
DropDownList1.DataSource = MyRst(query);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Please Select", ""));
}
public DataTable MyRst(string strSQL)
{
var rst = new DataTable();
using (SqlConnection conn = new SqlConnection((Session["MyCon"] as string)))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rst.Load(cmdSQL.ExecuteReader());
}
}
return rst;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// set connecting string from TEST4 to whatever database selected
string strCon = Session["MyCon"] as string;
string strDB = DropDownList1.SelectedItem.Value;
strCon = strCon.Replace("Initial Catalog = test4;", strDB);
Session["MyCon"] = strCon;
// now load 2nd cbo box list with all tables
string strSQL = #"SELECT TABLE_NAME FROM [" + strDB + "].INFORMATION_SCHEMA.TABLES " +
"WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME";
DropDownList2.DataSource = MyRst(strSQL);
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("Please Select", ""));
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
// send results to the Grid
string strSQL = "SELECT * FROM [" + DropDownList2.SelectedItem.Value + "]";
GridView1.DataSource = MyRst(strSQL);
GridView1.DataBind();
}
And now we get this:
So, I used a working connection string to a given database. I quite much assumed that the same information could and would connect to all of them, so I swap out TEST4 database name with any one we select.

Cascading dropdown not populating

I have been following the following example to create some cascading dropdowns in a web application. The example does not use jquery and I would like to stick with this for now.
https://www.aspsnippets.com/Articles/Populate-Cascading-DropDownList-from-Database-in-ASPNet-Example.aspx
I am having trouble getting my second dropdown to populate a list using the result from the first. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CategorySelect.Items.Clear();
CategorySelect.Items.Add(new ListItem("--Select Activity--", ""));
CategorySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["iSAMSConnectionString"].ConnectionString;
String strQuery = "select TblActivityManagerFolderID, txtName from dbo.TblActivityManagerFolder";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
CategorySelect.DataSource = cmd.ExecuteReader();
CategorySelect.DataTextField = "txtName";
CategorySelect.DataValueField = "TblActivityManagerFolderID";
CategorySelect.DataBind();
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void ActivitySelect_SelectedIndexChanged(object sender, EventArgs e)
{
ActivitySelect.Items.Clear();
ActivitySelect.Items.Add(new ListItem("--Select Activity--", ""));
ActivitySelect.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["iSAMSConnectionString"].ConnectionString;
String strQuery = "select txtName, TblActivityManagerGroupID from dbo.TblActivityManagerGroup " +
"where intFolder=#txtName";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#txtName",
CategorySelect.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ActivitySelect.DataSource = cmd.ExecuteReader();
ActivitySelect.DataTextField = "txtName";
ActivitySelect.DataValueField = "TblActivityManagerGroupID";
ActivitySelect.DataBind();
if (ActivitySelect.Items.Count > 1)
{
ActivitySelect.Enabled = true;
}
else
{
ActivitySelect.Enabled = false;
}
}
finally
{
con.Close();
con.Dispose();
}
}
I am using 2 tables.
TblActivityManagerFolder where I am using 2 fields - TblActivityManagerFolderID and txtName
TblActivityManagerGroup where I am using 2 fields - intFolder (which joins to TblActivityManagerFolderID) and txtName
My first drop down populates exactly as expected, but when I make a selection nothing at all happens in the 2nd dropdown.
Additional Code:
<asp:SqlDataSource ID="iSAMS" runat="server" ConnectionString="<%$ ConnectionStrings:iSAMSConnectionString %>"
SelectCommand="SELECT [blnActive], [TblActivityManagerFolderID], [txtName] FROM [TblActivityManagerFolder] WHERE ([intActivity] = #intActivity)">
<SelectParameters>
<asp:Parameter DefaultValue="34" Name="intActivity" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</div>
<div class="auto-style18">
<asp:DropDownList ID="CategorySelect" runat="server" DataTextField="txtName" DataValueField="TblActivityManagerFolderID"
OnSelectedIndexChanged="ActivitySelect_SelectedIndexChanged" CssClass="newStyle1">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="CategorySelect"
ErrorMessage="Please select your answer" style="text-align: left; font-weight: 700; color: #FF0000; font-size: medium;">!</asp:RequiredFieldValidator>
</div>
<br />
<div class="auto-style19">
<div class="auto-style20">
Please select the activity undertaken from the pick list:
<asp:DropDownList ID="ActivitySelect" runat="server" DataSourceID="iSAMSActivity" DataTextField="txtName" DataValueField="TblActivityManagerGroupId" CssClass="newStyle1" OnSelectedIndexChanged="ActivitySelect_SelectedIndexChanged">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ActivitySelect"
ErrorMessage="Please select your answer" style="text-align: left; font-weight: 700; color: #FF0000; font-size: medium;">!</asp:RequiredFieldValidator>
<asp:SqlDataSource ID="iSAMSActivity" runat="server" ConnectionString="<%$ ConnectionStrings:iSAMSConnectionString %>" SelectCommand="SELECT [txtName], [intActivity], [intFolder], [TblActivityManagerGroupId] FROM [TblActivityManagerGroup] WHERE ([intFolder] = #intFolder)">
<SelectParameters>
<asp:ControlParameter ControlID="CategorySelect" Name="intFolder" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
I am also posting back the results so I can see if this is working using:
protected void Button1_Click(object sender, EventArgs e)
{
var activity = CategorySelect.DataTextField;
var CoCActivity = ActivitySelect.DataTextField;
var OtherSkills = SkillsTextBox.Text;
var ExtraDev = DevTextBox.Text;
var OtherActivities = OtherActivitiesTextBox.Text;
OutputLabel.Text = activity + "<br/>" + CoCActivity + "<br/>" + OtherSkills + "<br/>" + ExtraDev + "<br/>" + OtherActivities;
}
When it is posting back, it is producing an integer rather than the label in the dropdown list. Can this be changed so it post backs the actual text?
Set the AutoPostBack property of the DropdownList to True. If you dont set it, the event would be only be triggered server side when other events force a postback (a button click or similar)

Object accepting method doesn't populate dropdown

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

Asp:Label that determined by dropdownlistbox not working properly

This was working the other day, not sure what happened but it isn't now and I cant figure it out. The label will only give me one item out of around 20(give or take) distinct items. No matter what I select in my drop down list, it always gives me that same value on the label.
HTML:
<td>
<asp:DropDownList ID="ddlCompanyCode" runat="server" CssClass="Dropdown" AutoPostBack="True" OnSelectedIndexChanged="ddlCompanyCode_SelectedIndexChanged" Width="139px" DataSourceID="CompanyCodeDS" DataTextField="CompanyCode" DataValueField="CompanyCode"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ddlCompanyCode" Display="Dynamic" ErrorMessage="*Please select a drop down list item." ForeColor="#CC0000" ValidationGroup="Submit"></asp:RequiredFieldValidator>
</td>
<td>
<asp:Label ID="lblSourceSyst" runat="server" CssClass="txtLabel" Text="Select Company Code" Width="137px" ></asp:Label>
</td>
<asp:SqlDataSource ID="CompanyCodeDS" runat="server" SelectCommandType="StoredProcedure" ConnectionString="<%$ ConnectionStrings:RptDatamartConnectionString %>" SelectCommand="[AXMap].[SelectCompanyCode_GLSourceCOA]">
</asp:SqlDataSource>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCompanyCode.Items.Add(new ListItem("--Please Select--", ""));
ddlCompanyCode.AppendDataBoundItems = true;
}
}
protected void ddlCompanyCode_SelectedIndexChanged(object sender, EventArgs e)
{
String connectionString = ConfigurationManager.ConnectionStrings["RptDatamartConnectionString"].ConnectionString;
String sqlStoredProc = "RptDatamart.AXMap.SelectCompanyCode_GLSourceCOA";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#CompanyCode", ddlCompanyCode.SelectedItem.Value);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlStoredProc;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
lblSourceSyst.Text = dataReader["SourceSystem"].ToString();
}
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}
And then the stored procedure im trying to use...
ALTER PROCEDURE [AXMap].[SelectCompanyCode_GLSourceCOA]
#CompanyCode varchar(10) = Null,
#SourceSystem nvarchar(255) = Null
AS
BEGIN
SET NOCOUNT OFF;
Select distinct CompanyCode, SourceSystem from [RptDatamart].[AXMap].[GLSourceCOA]
END
my sql might be terribly off, but i would think it would work.
lblSourceSyst.Text = dataReader["SourceSystem"].ToString();
Should be:
lblSourceSyst.Text += dataReader["SourceSystem"].ToString();

Gridview Search box in ASP.NET

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();
}

Categories