I have been Looking around this for 3 days so please, any feed back will be appreciated .
I have a parent repeater that pulls the expected data but i am trying to nest a child repeater, Find the Control and Populate the data. but so far it has not worked. For Some Reason the Nested Repeater Below Is Not Being picked Up to display The Proper Data.
Any Suggestions?
Asp.Net Code Is Here:
<asp:Repeater ID="EquipmentRepeater" runat="server" OnItemDataBound="Repeater2_ItemDataBound" >
<ItemTemplate>
<b>Equipment:</b>
<%# DataBinder.Eval(Container.DataItem, "Equip") %>
<%# DataBinder.Eval(Container.DataItem, "Location") %>
</ItemTemplate>
</asp:Repeater>
protected void Repeater2_ItemDataBound(object sender System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
SqlConnection con = new SqlConnection(ConString);
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater Repeater2 = (Repeater)e.Item.FindControl("EquipmentRepeater");
System.Data.DataTable ds = new System.Data.DataTable();
SqlCommand cmd1 = new SqlCommand(" Select HourID, Equip,Location FROM Equip where HourID=#id");
cmd1.Parameters.Add("#id", SqlDbType.Int).Value = id;
con.Open();
cmd1.Connection = con;
cmd1.ExecuteReader();
con.Close();
SqlDataAdapter ad = new SqlDataAdapter(cmd1);
// DataTable ds = new DataTable();
ad.Fill(ds);
con.Close();
//Need to assign the Data in datatable
Repeater2.DataSource = ds;
Repeater2.DataBind();
}
}
I solved It, There were 2 Problems:
1- The Repeater ItemDataBound Needed to be in the parent repeater Even Handler.
2-the second Problem was The Id Parameter Id for The Child repeater did Not have any value So Icreated a hidden filed In the Parent repeater for Id and called it on ItemDataBound
<asp:HiddenField ID="ID" runat="server" Value='<%# Eval("ID") %>' />
protected void Repeater2_ItemDataBound(object sender System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
SqlConnection con = new SqlConnection(ConString);
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater Repeater2 = (Repeater)e.Item.FindControl("EquipmentRepeater");
System.Data.DataTable ds = new System.Data.DataTable();
SqlCommand cmd1 = new SqlCommand(" Select HourID, Equip,Location FROM Equip where HourID=#id");
HiddenField id = (HiddenField)e.Item.FindControl("ID");
int parsedId = int.Parse(id.Value);
cmd1.Parameters.Add("#id", SqlDbType.Int).Value = parsedId;
con.Open();
cmd1.Connection = con;
cmd1.ExecuteReader();
con.Close();
SqlDataAdapter ad = new SqlDataAdapter(cmd1);
// DataTable ds = new DataTable();
ad.Fill(ds);
con.Close();
//Need to assign the Data in datatable
Repeater2.DataSource = ds;
Repeater2.DataBind();
}
}
thank You all and good luck
Related
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#
I am making an Employee Roster Scheduler.
Currently, I'm trying to use a repeater to display the current shifts in a calendar format.
Below is my current output:
As you can see, there are 2 shifts on Saturday. Does anyone know how I can place these two shifts under one header, so Saturday 03 June 2017 only appears once, rather than twice?
Below you can find my code:
HTML:
<div class="col-lg-12">
<asp:Repeater ID="repSubscription" runat="server" OnItemDataBound="repSubscription_ItemDataBound">
<ItemTemplate>
<div class="col-lg-2">
<div class="panel panel-default">
<div class="panel-heading" style="background-color: #3A6EA5; color: white">
<h4 class="panel-title">
<%# Eval("Start_Time", "{0:dddd, dd MMMM yyyy}") %>
</h4>
</div>
<!--panel-heading-->
<div class="panel-body">
<asp:Repeater ID="repShift" runat="server">
<ItemTemplate>
<b><%# Eval("Job_Title") %></b>
</ItemTemplate>
</asp:Repeater>
</br>
<asp:Repeater ID="repEmp" runat="server">
<ItemTemplate>
<%# Eval("Employee_Name") %>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Repeater ID="repTimes" runat="server">
<ItemTemplate>
<%# Eval("Start_Time", "{00:HH:MM}") %> - <%# Eval("End_Time" , "{00:HH:MM}") %>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
this.bindRepeater();
}
private void bindRepeater()
{
conn = new SqlConnection(connectionString);
conn.Open();
comm = new SqlCommand("SELECT DISTINCT Start_Date, End_Date FROM My_Subscription WHERE Subscription_Id = 1", conn);
SqlDataReader reader1 = comm.ExecuteReader();
while (reader1.Read())
{
startDate = Convert.ToDateTime(reader1["Start_Date"]);
endDate = Convert.ToDateTime(reader1["End_Date"]);
//lblError.Text += startDate.ToString() + "<br/>" + endDate.ToString();
}
conn.Close();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT Start_Time, Emp_ID, Job_ID, Emp_Sch_Id FROM My_Employee_Schedule WHERE Start_Time BETWEEN #startReportDate AND #endReportDate", con))
{
cmd.Parameters.AddWithValue("#startReportDate", startDate);
cmd.Parameters.AddWithValue("#endReportDate", endDate);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
repSubscription.DataSource = dt;
repSubscription.DataBind();
}
}
}
}
protected void repSubscription_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
conn = new SqlConnection(connectionString);
conn.Open();
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater repBusiness = (Repeater)(e.Item.FindControl("repShift"));
SqlCommand cmd = new SqlCommand("SELECT Job_Title FROM My_Job_Type WHERE Job_Type_Id=#Job_Type_Id");
string Group_Id = DataBinder.Eval(e.Item.DataItem, "Job_ID").ToString();
cmd.Parameters.AddWithValue("#Job_Type_Id", Group_Id);
//Need to assign the Data in datatable
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
repBusiness.DataSource = dt;
repBusiness.DataBind();
}
conn.Close();
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater repTimes = (Repeater)(e.Item.FindControl("repTimes"));
SqlCommand cmd = new SqlCommand("SELECT Start_Time, End_Time FROM My_Employee_Schedule WHERE Emp_Sch_Id=#EmpSchId");
string Group_Id = DataBinder.Eval(e.Item.DataItem, "Emp_Sch_Id").ToString();
cmd.Parameters.AddWithValue("#EmpSchId", Group_Id);
//Need to assign the Data in datatable
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
repTimes.DataSource = dt;
repTimes.DataBind();
}
conn.Open();
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater repEmp = (Repeater)(e.Item.FindControl("repEmp"));
SqlCommand cmd = new SqlCommand("SELECT Employee_Name FROM My_Employee WHERE Employee_Id=#EmpId");
string Group_Id = DataBinder.Eval(e.Item.DataItem, "Emp_ID").ToString();
cmd.Parameters.AddWithValue("#EmpId", Group_Id);
//Need to assign the Data in datatable
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
repEmp.DataSource = dt;
repEmp.DataBind();
}
conn.Close();
}
, then I am happy to post it.
Thanks a lot for any help in advance!
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();
}
}
}
this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.
i try to add values in dropdownlist in gridview query works fine but it appears as this ..
gridview html
<asp:BoundField HeaderText="ApproveID" DataField="ApproveID" ></asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#
Eval("ApproveID") %>' Visible = "false" />
<asp:DropDownList ID="DropDownList4" runat="server"
class="vpb_dropdown">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("DropDownList4") as
DropDownList);
ddlCountries.DataSource = GetData("SELECT ApproveID,ApproveType FROM
ApproveType");
ddlCountries.DataTextField = "ApproveType";
ddlCountries.DataValueField = "ApproveID";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
//Select the Country of Customer in DropDownList
//string country = (e.Row.FindControl("lblCountry") as Label).Text;
//ddlCountries.Items.FindByValue(country).Selected = true;
}
}
values are not inside in dropdownlist ..how to show values in dropdown??
and when i debug the code it cant show me any error
getdata code
private DataSet GetData(string query)
{
string conString =
ConfigurationManager.ConnectionStrings["mydms"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
Set
DropDownList1.SelectedValue = "Some Value";
then you will get the value as default
Get data function returns null or empty value so it wont through error or exception while debugging.Your code working fine better check data in the database.
In a project I participated we returned the DataTable instead of DataSet and it was working fine with dropdowns. We had code like this:
if( ds.Tables.Count == 1)
return ds.Tables[0];
else
return new DataTable();
Besides I would change the way of databinding. In my opinion using ObjectDataSource is a better approach becuase the event is called only when the data is needed and you don't have to do checks like this:
if (e.Row.RowType == DataControlRowType.DataRow)
After your last comment you should check if the DataSet contains the record you want ot set as selected:
if (ddlCountries.Items.FindByValue(country) != null)
{
ddlCountries.Items.FindByValue(country).Selected = true;
}