ASP.net: ReportViewer not displaying (parameters from dynamically created textboxes) - c#

I have an existing code that displays a reportserver RDL report in a reportviewer. I prompt the user for inputs and those are then passed as parameters to a store procedure in Sql Server.
The report generates properly as proof of concept with hard-coded number of textboxes, but obviously not all reports will have the same number of parameters. So here is my working code and the screenshot:
Working Report
ASP.NET
<%# Page Language="C#" Trace="true" AutoEventWireup="true" CodeBehind="Reports.aspx.cs" Inherits="FormsAuthAd.Reports" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="reports-body">
<head runat="server">
<title>Reports</title>
<link href="../css/Style.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div class="params-container container">
<asp:TextBox ID="txtStart" runat="server" placeholder="From Date" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtEnd" runat="server" placeholder="To Date" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtBrand" runat="server" placeholder="Brand" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtSeason" runat="server" placeholder="Season" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtComp" runat="server" placeholder="Company" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtLoc" runat="server" placeholder="Location" class="input-fields"></asp:TextBox>
<asp:TextBox ID="txtLine" runat="server" placeholder="Line" class="input-fields"></asp:TextBox>
<asp:Button ID="btnShow" runat="server" OnClick="Button1_Click" Text="Generate" class="input-fields"/>
</div>
<div class="rpt-container container">
<rsweb:ReportViewer ID="rptVwr" runat="server" CssClass="rpt-viewer"></rsweb:ReportViewer>
</div>
</form>
</body>
</html>
CODE BEHIND
private void showReport()
{
rptVwr.Reset();
DataTable dt = GetData(txtStart.Text, txtEnd.Text, txtBrand.Text, txtSeason.Text, txtComp.Text, txtLoc.Text);
rptVwr.Visible = true;
ReportDataSource rds = new ReportDataSource("DataSet2", dt);
rptVwr.LocalReport.DataSources.Add(rds);
rptVwr.LocalReport.ReportPath = "../ReportServer/StockExport.rdl";
ReportParameter[] rptParams = new ReportParameter[]
{
new ReportParameter("StartDate",txtStart.Text),
new ReportParameter("EndDate",txtEnd.Text),
new ReportParameter("Brand",txtBrand.Text),
new ReportParameter("Season",txtSeason.Text),
new ReportParameter("Company",txtComp.Text),
new ReportParameter("Store",txtLoc.Text),
};
rptVwr.LocalReport.SetParameters(rptParams);
rptVwr.LocalReport.Refresh();
}
private DataTable GetData(string fromDate, string toDate, string brandCode, string seasonCode, string compCode, string locCode)
{
DataTable dt = new DataTable();
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings ["ReportServerConnStr"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("sp_valueEntryStock", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#StartDate", SqlDbType.NVarChar).Value = fromDate;
cmd.Parameters.Add("#EndDate", SqlDbType.NVarChar).Value = toDate;
cmd.Parameters.Add("#Season", SqlDbType.NVarChar).Value = seasonCode;
cmd.Parameters.Add("#Brand", SqlDbType.NVarChar).Value = brandCode;
cmd.Parameters.Add("#Company", SqlDbType.NVarChar).Value = compCode;
cmd.Parameters.Add("#Store", SqlDbType.NVarChar).Value = locCode;
cmd.CommandTimeout = 1000;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
showReport();
}
Obviously, I did not want a hard-coded number of textboxes so I tweaked my code to dynamically add textboxes on page load based on a table in Sql Server.Here is my existing code and screenshot:
Page after submitting parameters
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [FieldNum],[FieldName],[AspId],[SqlParameter] FROM [MIS_FieldsMaster]", con))
{
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dtable);
int i = 0;
foreach (DataRow dr in dtable.Rows)
{
TextBox tb = new TextBox();
tb.ID = dr["AspId"].ToString().Trim();
stringArray[i] = dr["SqlParameter"].ToString().Trim();
tb.Text = stringArray[i];
ph1.Controls.Add(tb);
i++;
}
}
}
}
private void showReport()
{
rptVwr.Reset();
DataTable dt = GetData();
rptVwr.Visible = true;
ReportDataSource rds = new ReportDataSource("DataSet2", dt);
rptVwr.LocalReport.DataSources.Add(rds);
rptVwr.LocalReport.ReportPath = "../ReportServer/StockExport.rdl";
rptVwr.LocalReport.Refresh();
}
private DataTable GetData()
{
DataTable dt = new DataTable();
int i = 0;
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["ReportServerConnStr"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("sp_valueEntryStock", cn);
cmd.CommandType = CommandType.StoredProcedure;
foreach (TextBox textBox in ph1.Controls.OfType<TextBox>())
{
cmd.Connection = cn;
cmd.Parameters.AddWithValue("#" + stringArray[i], textBox.Text);
i++;
}
cmd.CommandTimeout = 1000;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
showReport();
}
So it does not even show me any error message so I do not really know where to look. I debugged the new code and I believe it is retrieving the data in the stored procedure because the local variable shows rows retrieved under datatable dt. The only thing is the report does not show in the reportViewer. It does not even show report toolbars.
Row retrieved from datatable dt
I would greatly appreciate any help. Thanks.

I figured out the reason for the report not displaying in the reportviewer.
It seems that I still need to add the parameters and set it to the reportviewer, like in my first working code:
ReportParameter[] rptParams = new ReportParameter[]
{
new ReportParameter("StartDate",txtStart.Text),
new ReportParameter("EndDate",txtEnd.Text),
new ReportParameter("Brand",txtBrand.Text),
new ReportParameter("Season",txtSeason.Text),
new ReportParameter("Company",txtComp.Text),
new ReportParameter("Store",txtLoc.Text),
};
rptVwr.LocalReport.SetParameters(rptParams);
Obviously =, it still needs to be dynamic so here is the code that I used:
List<ReportParameter> paramList = new List<ReportParameter>();
int i = 0;
foreach (TextBox textBox in ph1.Controls.OfType<TextBox>())
{
paramList.Add(new ReportParameter(stringArray[i], textBox.Text));
i++;
}
rptVwr.LocalReport.SetParameters(paramList);
Now, I am able to generate the dynamic textboxes and at the same time pass the values in those textboxes to my sql server stored procedure and finally generate and display the report based on the same textboxes.
I would consider this solved, but I just have a niggling question in my head:
Why didn't my code work when it is exactly the same (at least logically if not syntactically) as the code in the youtube example that I took: Two way to pass parameter in stored procedure and display the output in Report Viewer using C#

Related

Performing Actions by Clicking on Button inside Repeater

I have a Repeater displaying rows from an SQL Server database.
I have an Edit and Delete button appearing in each row, but I can't successfully write code behind these buttons.
Here is the code to display the repeater:
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<div>
<table>
<tr><th><%#Eval("Event_Title")%></th><td><asp:Button ID="LinkButton1" runat="server" CommandName="Edit" Text="Edittttt"></asp:Button></td><td><button>Delete</button></td></tr>
<tr><td>Event Group ID</td><td><%#Eval("Event_Group_Id") %></td></tr>
<tr><td>Event Type</td><td><%#Eval("Event_Type") %></td></tr>
<tr><td>Event ID</td><td><%#Eval("Event_Id") %></td></tr>
<br />
</table>
</div>
</ItemTemplate>
</asp:Repeater>
And here is the UI.
I have tried to use the below code to see if the Edit button is working:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "Edit":
Response.Write("Edit button clicked");
break;
default: break;
}
}
But I am getting this error message:
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Below is my Page_Load code:
I understand that a lot of it is duplicated, but I will tidy this up in time. Can anyone advise me what I need to do?
//Trying to display events using repeater
SqlConnection connR;
string connectionStringR = ConfigurationManager.ConnectionStrings[
"BallinoraDBConnectionString1"].ConnectionString;
connR = new SqlConnection(connectionStringR);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Events", connR);
DataTable dt = new DataTable();
sda.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
Response.Write("Hello");
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings[
"BallinoraDBConnectionString1"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand( //where Event_Group = 'Upcoming
"SELECT Event_Id, Event_Group_Id, Event_Type, Event_Title FROM Events WHERE Event_Group_Id = 1",
conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
if (lblGroupOneEvents.Text == "")
{
while (reader.Read())
{
lblGroupOneEvents.Text += "<div> <table> <tr><td>" + reader["Event_Title"] + "</td>" + "</tr><tr><td><button>Delete</button></td></tr></table> </div>";
}
// lblTest.Text += reader["Event_Id"] +"<br />";
}
else
{
;
}
reader.Close();
conn.Close();
SqlConnection conn1;
SqlCommand comm1;
string connectionString1 = ConfigurationManager.ConnectionStrings[
"BallinoraDBConnectionString1"].ConnectionString;
conn1 = new SqlConnection(connectionString);
comm1 = new SqlCommand( //where Event_Type = 'Upcoming
"SELECT Event_Id, Event_Group_Id, Event_Type, Event_Title FROM Events WHERE Event_Group_Id = 2",
conn);
conn.Open();
SqlDataReader reader1 = comm1.ExecuteReader();
while (reader1.Read())
{
lblGroupTwoEvents.Text += reader1["Event_Title"] + "<br />";
// lblGroupTwoEventsType.Text += reader1["Event_Id"] + "<br />";
}
reader.Close();
conn.Close();

Binding data dynamically in ListView2 on Selected_indexChanged() of ListView1

I am working in a project where i need to list the database child items in listview2 who's parent items reside in listview1 already. here is my listview1 code;
<asp:ListView
ID="ListView1"OnSelectedIndexChanged="ListView1_SelectedIndexChanged" runat="server">
<ItemTemplate>
<a href='<%# Eval("Module_Redirect") %>'> <img src="<%#
Eval("Module_img") %>" /> </a>
</ItemTemplate>
the .cs page code is as follow(which is not working yet!)
protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ListView1.SelectedIndex == 3)
{
SqlDataAdapter da2 = new SqlDataAdapter();
da2.SelectCommand = new SqlCommand("select * from tbl_Forms where Module_ID=3 ", conn);
DataTable dt2= new DataTable();
da2.Fill(dt2);
ListView2.DataSource = dt2;
ListView2.DataBind();
}
}
My point is: how can in fetch the selected item templete of listview1 and show the relevent record in listview2?
you can try this.
using (SqlConnection con = new SqlConnection("YourConnectioString"))
{
using (SqlDataAdapter da2 = new SqlDataAdapter { SelectCommand = new SqlCommand("select * from tbl_Forms where Module_ID = #Module_ID ", con) })
{
// as your using index as the parameter,,
da2.SelectCommand.Parameters.AddWithValue("#Module_ID", ListView1.SelectedIndex);
// or if your trying to pass parameter Module_ID from ListView1 DataKey ,, you can use SelectedDataKey
//da2.SelectCommand.Parameters.AddWithValue("#Module_ID", ListView1.SelectedDataKey);
using (DataTable dt2 = new DataTable())
{
con.Open();
da2.Fill(dt2);
ListView2.DataSource = dt2;
ListView2.DataBind();
}
}
}

Deleting checked records from table in asp.net [closed]

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";
}
}

Displaying a list of hyperlink from database with c#/asp.net

I'm an asp.net / c# newbie and i'm trying to create a very simple menu that is generated from my database.
so far i have managed to extract the table from database and into a data table and from there to an array.
My problem is that i haven't figured out how to use the data in a loop in my page (the menu changes according to user types).
I tried using <% =Array %> but i can't seem to use that inside a while/for loop or even assignment line.
Maybe i'm attacking this the wrong way , i guess my question is basically this:
How can i use the data i gather from the database (names , urls) in my dynamic page?
here is my current code behind:
public string[] keep = new string[100];
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Response.Write("response in postback");
getMenu();
}
}
void getMenu()
{
Response.Write("response in getmenue");
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=(local);database=PhilipsMaterials;Integrated Security=SSPI;";
con.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string sql = "Select * from Materials";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
dt = ds.Tables[0];
DataRow[] drowpar = dt.Select();
int i = 0;
foreach (DataRow dr in drowpar)
{
keep[i] = dr["Material Name"] as string;
i = i + 1;
}
con.Close();
}
Thank you.
You just need to use a data contol like gridview or repeater.You can then bind dataset to those control's datasource property. From my point of view repeater will be best datacontro for dynamic menu..
here is mark up for repeater
<asp:Repeater ID="Rept" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li><a href='<%#Eval("url") %>'><%#Eval("names") %></a></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
and here is code to bind dataset
Rept.DataSource = ds;
Rept.DataBind();
A nice and clear way, that is also compatible with header, and UpdatePanel is to use a Literal control inside the page and render on it your menu.
Place a literal somewhere in your page:
<asp:Literal runat="server" ID="txtInfo" EnableViewState="false" />
Then render on code behind your data using a StringBuilder and then place it on this Literal as:
StringBuilder sbRenderOnMe = new StringBuilder();
sbRenderOnMe.Append("<br> Some Text");
txtInfo.Text = sbRenderOnMe.ToString();
Your code will be for example as:
using(SqlConnection con = new SqlConnection())
{
con.ConnectionString = "server=(local);database=PhilipsMaterials;Integrated Security=SSPI;";
con.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string sql = "Select * from Materials";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
dt = ds.Tables[0];
DataRow[] drowpar = dt.Select();
StringBuilder sbRenderOnMe = new StringBuilder();
foreach (DataRow dr in drowpar)
{
sbRenderOnMe.AppendFormat("Some Menu Names : {0}", dr["Material Name"]);
}
con.Close();
}
txtInfo.Text = sbRenderOnMe.ToString();
Some notes: Do not use the Response.Write especial from code behind, because you probably write before the first bytes of the page. The Response.Write is direct write on the output - In your case you won to create some data and place them somewhere specific on your page, the Response.Write can not help, can not work on that from code behind because is just direct write on the page.

How to make an autocomplete TextBox in ASP.NET?

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.

Categories