Binding data dynamically in ListView2 on Selected_indexChanged() of ListView1 - c#

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

Related

Trying to store List View ID

i'm trying to store the id number of records from the list view table thru check box and other values, and I got this error after i hit the submit button. It says there is a null.
Here is the populate the table:
void GetEmployees()
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"SELECT EmployeeID, FirstName, LastName, Position FROM
Employees ";
using (SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeID");
lvEmployees.DataSource = ds;
lvEmployees.DataBind();
con.Close();
}
}
}
Here is the submit click code:
protected void btnAddParticipants_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in this.lvEmployees.Items)
{
string idValue = lvEmployees.DataKeys[item.DataItemIndex].Value.ToString();
if (item.ItemType == ListViewItemType.DataItem)
{
CheckBox cb = (CheckBox)item.FindControl("cbEmpPart");
if (cb.Checked)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"INSERT INTO CourseParticipants VALUES (#TrainingModuleID, #EmployeeID, #Active, #DateAdded)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("#EmployeeID", 1);
cmd.Parameters.AddWithValue("#Active", 1);
cmd.Parameters.AddWithValue("#DateAdded", DateTime.Now);
cmd.ExecuteNonQuery();
//con.Close();
}
}
}
}
}
}
Here is the .aspx
<asp:ListView ID="lvEmployees" runat="server" OnPagePropertiesChanging="lvEmployees_PagePropertiesChanging" OnDataBound="lvEmployees_DataBound">
<ItemTemplate>
<tr>
<td><%# Eval("FirstName")%>,<%# Eval("LastName")%></td>
<td><%# Eval("Position")%></td>
<td>
<asp:CheckBox ID="cbEmployee" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Start by adding the DataKeyNames to the ListView on the aspx page.
<asp:ListView ID="lvEmployees" runat="server" DataKeyNames="EmployeeID">

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

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#

C# Nested Repeater not Working

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

Asp.net dropdownlist getselectedvalue doesnt return anything

Im having a problem with a dropdownlist in asp.net.
When i try to get the selected value of the list it doesnt return anything.
The aspx looks like this
<div class="form-signin">
<h2 class="form-signin-heading">Slet besked</h2>
<div class="input-group">
<span class="input-group-addon">ID</span>
<asp:dropDownList runat="server" CssClass="form-control" ID="sletBox" />
</div>
<asp:Button runat="server" CssClass="btn btn-lg btn-block btn-danger" Text="Slet" OnClick="Slet" />
</div>
And the kode behind it looks like this
protected void Slet(object sender, EventArgs e)
{
Response.Write("wow der sker noget");
Response.Write(sletBox.SelectedItem.Value);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection myconnection = new SqlConnection();
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder();
myconnection.ConnectionString = constr;
myconnection.Open();
string sqlcmd = "DELETE FROM messages WHERE messageid = '" + sletBox.SelectedValue.ToString() + "'";
SqlCommand messageDelete = new SqlCommand(sqlcmd, myconnection);
messageDelete.ExecuteNonQuery();
myconnection.Close();
}
The only thing that works is the response.write(wow) not the selectedvalue
EDIT:
The page_load code
protected void Page_Load(object sender, EventArgs e)
{
DataTable subjects = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}
You're doing the databinding for the dropdownlist in the pageload and not checking for IsPostBack. As a result when the button triggers the clik it resets the selectedvalue. Change you PageLoad like below
if (!IsPostBack)
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}
As a side note as Mathew suggested try adding using to better manage your connections objects so it's properly disposed after it's been used.
You must load your DropDownList data only if IsPostBack is false, otherwise you'll be reloading the control every postback. Once the data bound to the control is changed, the selected value is lost as well. Keep in mind that the Page_Load event is fired when the SelectedIndexChanged event occurs.
if(!Page.IsPostBack)
{
DataTable subjects = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT messageId, messageText FROM messages", con);
adapter.Fill(subjects);
sletBox.DataSource = subjects;
sletBox.DataTextField = "messageText";
sletBox.DataValueField = "messageId";
sletBox.DataBind();
}
sletBox.Items.Insert(0, new ListItem("Vælg besked", ""));
}

How to keep Dropdown value same after refresh the page

I am using three dropdowns, in first dropdown i bind data from sql. In second dropdown i also bind data from sql and the third dropdown is bind according to second dropdown so in second dropdown there is autopostback property true. I have one search button which fetch the result from database on click.
I want to keep all the Dropdownlist value same after my result show on the page. One thing i did is, at the time of button click i make the session and check it at page load when it is not null bind the dropdown value. Till this point it is working fine i am able to bind prevoius selected values.
This is in my master page and result are display in result page, which is using this masterpage.
aspx :
<asp:DropDownList ID="dd_category" runat="server" AutoPostBack="True"
onselectedindexchanged="dd_category_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="dd_subcategory" runat="server" ></asp:DropDownList>
<asp:Button ID="but_go" runat="server" Text="Go" onclick="but_go_Click"/>
page load :
if (!IsPostBack)
{
FillStates();
FillCategory();
}
if (Session["state"] != null)
{
dd_state.SelectedValue = (string) Session["state"];
}
aspx.cs :
private void FillStates()
{
SqlCommand cmd = new SqlCommand("sps_bindcountrystate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 2);
cmd.Parameters.AddWithValue("#CountryID", 1);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_state.DataSource = objDs.Tables[0];
dd_state.DataTextField = "s_name";
dd_state.DataValueField = "s_id";
dd_state.DataBind();
dd_state.Items.Insert(0, "Select State");
}
}
protected void dd_category_SelectedIndexChanged(object sender, EventArgs e)
{
int CategoryID = Convert.ToInt32(dd_category.SelectedValue);
FillSubCategory(CategoryID);
}
private void FillCategory()
{
SqlCommand cmd = new SqlCommand("sps_bindcategory", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 1);
cmd.Parameters.AddWithValue("#CategoryID", 0);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_category.DataSource = objDs.Tables[0];
dd_category.DataTextField = "category_name";
dd_category.DataValueField = "category_id";
dd_category.DataBind();
dd_category.Items.Insert(0, "Select Category");
dd_subcategory.Items.Insert(0, "Select Sub-Category");
}
}
private void FillSubCategory(int CategoryID)
{
SqlCommand cmd = new SqlCommand("sps_bindcategory", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 2);
cmd.Parameters.AddWithValue("#CategoryID", CategoryID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_subcategory.DataSource = objDs.Tables[0];
dd_subcategory.DataTextField = "subcategory_name";
dd_subcategory.DataValueField = "subcategory_id";
dd_subcategory.DataBind();
dd_subcategory.Items.Insert(0, "Select Sub-Category");
}
}
protected void but_go_Click(object sender, EventArgs e)
{
Session["state"] = dd_state.SelectedValue;
Session["category"] = dd_category.SelectedValue;
Session["subcategory"] = dd_subcategory.SelectedValue;
Response.Redirect("Results.aspx");
}
Now problem is when i again choose some different value in first dropdown and try to choose different value in second dropdown, the second dropdown is having postback so it refreshes page and according to session state it changes my first dropdown value back to prevoius one.
Tell me what to do so that new selected value does'nt change due to page refresh.

Categories