The name 'DataList1' does not exist in the current context - c#

I get the following error in a page:
'The name 'DataList1' does not exist in the current context'
Here is my code:
listviewvideo.aspx.cs
private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from uploadvideo";
cmd.Connection = con;
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
listviewvideo.aspx
<table>
<tr>
<td>
<ASPNetFlashVideo:FlashVideo ID="FlashVideo1" runat="server" Height="500" Width="1050"></ASPNetFlashVideo:FlashVideo>
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="myButton" />
<asp:Button ID="btnupload" runat="server" Text="Upload" OnClick="btnupload_Click" CssClass="myButton" />
<hr />
<asp:DataList ID="DataList1" Visible="true" runat="server" AutoGenerateColumns="false" RepeatColumns="2" CellSpacing="5">
<ItemTemplate>
<u>
<%# Eval("Name") %>
</u>
<a class="player" style="height:300px; width:300px; display:block" href='<%# Eval("Id","FileCS.ashx?Id={0}") %>'></a>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
I get the following error in a page:
'The name 'DataList1' does not exist in the current context'

You might get this error. There 3 solutions for this
Save your project and close the Solution, close the IIS Express also. And check whether it works or not.
Try adding the the datalist by writing below code in your listviewvideo.aspx.designer.cs page of where you are adding the Datalist item.
Check your code behind file name and Inherits property on the #Page directive, make sure they both match.
Also you can have a look here for more clear picture
ID Does not exist in the current context
protected global::System.Web.UI.WebControls.DataList Datalist1;
Hope this helps.

Related

How to store information in the view list in the database

How can I save rows created in the list view in my database? How can I access the values ​​in the (list view)? How to save the values ​​created in the view list to the database?
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate runat="server">
<tr class="text-center">
<td class="product-remove"></td>
<td class="image-prod">
<div class="">
<asp:Image ID="Image1" CssClass=" img" ImageUrl='<%# "../img/" + Eval("picture" )%>' runat="server" />
</div>
</td>
<td class="product-name"><%# Eval("namebook") %> </td>
<td id="t_Plural" runat="server" class="price "><%# Eval("Price") %> </td>
<td class="quantity"><%# Eval("titel") %></td>
<td class="col-2">
<asp:Button ID="delete" CssClass="btn btn-outline-danger" CommandArgument='<%# Eval("id")%>' OnClick="delete_Click" runat="server" Text="حذف کالا" />
</td>
<td>
<%-- <input id="quantity2" runat="server" type="number" AutoPostBack="true" oninput="lod_gheymat" onserverclick="lod_gheymat" value="" min="1" max="20" />--%>
<asp:TextBox ID="quantity2" runat="server" CssClass="input-wrap" AutoPostBack="true" OnTextChanged="lod_gheymat" Text="1" min="1" max="20"></asp:TextBox>
</td>
<td >
<div class="row">
<asp:Label ID="lbl_Plural" runat="server" Text="0"></asp:Label> <span class="row"> تومان</span>
</div>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
The way to approach this type of issue and problem is to NOT try and add to the database from the list view.
What you do is get your data (say in a data table).
then send the data table to the list view.
Now, if you want say a "add new row" button?
Add the row to the data table, and then re-bind the list view.
Next up?
You asking how to add this to the database, but is not that where it came form in the first place?
and it is VERY confusing that you asking how to add rows to this LV, but how is the user going to add the picture?
Next up, how is this post getting up-votes? I will assume up-votes are not being messed with? I'll put this issue aside, but something not fitting here.
Ok, so, how to add rows, and how to save such rows back to the database?
You can achieve this goal this way:
First, we assume the LV can now be freely edit. That means using text boxes.
so, we have this markup:
(probably not HUGE important the LV you have, but the "idea" outlined here should work fine).
<style> .borderhide input, textarea {border:none}</style>
<div style="width:70%;padding:20px">
<h2>Fighter Prints</h2>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<ItemTemplate>
<tr style="">
<td><asp:TextBox ID="Fighter" runat="server" Text='<%# Eval("Fighter") %>' TextMode="MultiLine" /></td>
<td><asp:TextBox ID="Engine" runat="server" Text='<%# Eval("Engine") %>' TextMode="MultiLine" Width="200px" /></td>
<td><asp:TextBox ID="Thrust" runat="server" Text='<%# Eval("Thrust") %>' Width="70px" /></td>
<td><asp:TextBox ID="Description" runat="server" Text = '<%#Eval("Description") %>'
TextMode="MultiLine" Width="340px" Rows="5" /></td>
<td>
<asp:Image ID="iPreview" runat="server" Height="68px" Width="149px"
ImageUrl='<%# Eval("ImagePath") %>'/>
</td>
<td><asp:TextBox ID="Qty" runat="server" Text='<%# Eval("Qty") %>' style="width:30px;text-align:right"/></td>
<td><asp:TextBox ID="Price" runat="server" Text='<%# string.Format("{0:c2}",Eval("Price")) %>' style="Width:70px;text-align:right"/></td>
<td><asp:TextBox ID="Total" runat="server" Text='<%# string.Format("{0:c2}",Eval("Total")) %>' style="Width:70px;text-align:right" /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server"
class="table table-hover borderhide ">
<tbody>
<tr runat="server" style="" >
<th runat="server">Fighter</th>
<th runat="server">Engine</th>
<th runat="server">Thrust (lbs)</th>
<th runat="server">Description</th>
<th runat="server">Preview</th>
<th runat="server" style="text-align:right">Qty</th>
<th runat="server" style="width:70px;text-align:right">Price</th>
<th runat="server" style="width:70px;text-align:right">Total</th>
</tr>
<tr id="itemPlaceholder" runat="server" />
</tbody>
<tfoot>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td><td>Total</td>
<td><asp:TextBox ID="MyTotal" runat="server" Text="0" Width="70px" Style="text-align:right"></asp:TextBox></td>
</tr>
</tfoot>
</table>
</LayoutTemplate>
</asp:ListView>
Ok, so the code to load is now this:
DataTable rstData = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
Session["rstData"] = rstData;
}
else
rstData = Session["rstData"] as DataTable;
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
{
conn.Open();
rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
rstData.Columns.Add("Total", typeof(decimal),"[Qty] * [Price]");
ListView1.DataSource = rstData;
ListView1.DataBind();
decimal myTotal = 0;
foreach (ListViewItem OneRow in ListView1.Items)
{
TextBox MyPrice = OneRow.FindControl("Total") as TextBox;
myTotal += Decimal.Parse(MyPrice.Text, NumberStyles.Currency);
}
// now update the final total label
TextBox lblTotal = ListView1.FindControl("MyTotal") as TextBox;
lblTotal.Text = string.Format("{0:c2}", myTotal);
}
}
}
And now we have this:
Ok, for the above, note how we added 3 buttons below the LV.
And becuase I wanted "cute" icons in the buttons, I dropped in hteml buttons, not asp.net ones. But, with a "id" and runat=server, they work JUST the same anyway.
So, our 3 buttons are (right after the LV markup)
<div style="float:left">
<button id="cmdSave" runat="server" class="btn" onserverclick="cmdSave_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-save"></span> &nbspSave
</button>
<button id="cmdUndo" runat="server" class="btn" style="margin-left:10px" onserverclick="cmdUndo_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-retweet"></span> &nbspUn do
</button>
</div>
<div style="float:right">
<button id="cmdAddNew" runat="server" class="btn" onserverclick="cmdAddNew_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-new-window"></span> &nbspAdd New
</button>
</div>
Ok, so of the 3, the un-do button code is easy:
protected void cmdUndo_ServerClick(object sender, EventArgs e)
{
// undo changes - just re-load the lv
LoadGrid();
}
Ok, now the save button. This save button will:
save any new rows, and ALSO save any editing we do. Remember, since we used text boxes, then I can quite much tab around - edit ANY row. If I hit save, then we save all edits AND ALSO any new row added.
So, the save button does this:
protected void cmdSave_ServerClick(object sender, EventArgs e)
{
GridToTable(); // send lv to table
SaveToDatabase();
}
So, now we need the routine to send the LV to the table. That code is this:
void GridToTable()
{
// pull grid rows back to table.
foreach (ListViewItem rRow in ListView1.Items)
{
int RecordPtr = rRow.DataItemIndex;
DataRow OneDataRow;
OneDataRow = rstData.Rows[RecordPtr];
OneDataRow["Fighter"] = ((TextBox)rRow.FindControl("Fighter")).Text;
OneDataRow["Engine"] = ((TextBox)rRow.FindControl("Engine")).Text;
OneDataRow["Thrust"] = ((TextBox)rRow.FindControl("Thrust")).Text;
OneDataRow["Description"] = ((TextBox)rRow.FindControl("Description")).Text;
OneDataRow["Qty"] = ((TextBox)rRow.FindControl("Qty")).Text;
OneDataRow["Price"] = Decimal.Parse(((TextBox)rRow.FindControl("Price")).Text,
NumberStyles.Currency);
}
}
So, the above takes ANY edit - any row you edit, and send changes from LV->rstData.
So, now we need the rstData save all rows, all edits, all additions back to the database, and that code is this:
void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters", conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
So, now that is quite much all we need.
The last button, "add row" is also easy, and looks like this:
protected void cmdAddNew_ServerClick(object sender, EventArgs e)
{
// user might have done some editing, so, pull LV to table
// just in case
GridToTable();
// add new row to database
DataRow MyNewRow = rstData.NewRow();
// setup some defaults and values for this new row
//MyNewRow["DateCreate"] = DateTime.Now;
rstData.Rows.Add(MyNewRow);
ListView1.DataSource = rstData;
ListView1.DataBind();
}
That is it. So, if I am looking at above LV, and hit add-new, we now have this:
so I can just fill out the information, and then hit save. If I hit un-do, then the row will not be added (nor saved).
Note how we had a min of code to do the save. Note how we did not mess with a boatload of templates (and thus save world poverty).
So, this works really nice, was not a lot of code and the real secrets "idea" here was persisting the rstData. This allows great ease of adding new rows, but MORE important it was very simple then to send the edits back to the database, and that one save command will not only save any editing in the LV, but also will create the new rows in the database for you. So, you can quite much tab around in that lv - almost like excel. So we don't have a huge mess of "edit" buttons, and all that jazz. Just a simple grid of data, and a simple save, or add new button.
Note VERY careful how the GridToTable works. As this shows HOW to grab, and get values from the LV, and that was quite much the "major" part of your question. So, you can grab any row of the LV, but to pull values out of the one row, you have to use "FindControl".
protected void savetodatabase_Click(object sender, EventArgs e)
{
System.Web.UI.HtmlControls.HtmlGenericControl Labelid;
TextBox quantity2;
foreach (ListViewItem rRow in ListView1.Items)
{
itemlist iteml = new itemlist();
quantity2 = (TextBox)rRow.FindControl("quantity2");
Labelid = (System.Web.UI.HtmlControls.HtmlGenericControl)rRow.FindControl("Labelid");
iteml.quantity = quantity2.Text;
iteml.bookid = Convert.ToInt32(Labelid.InnerText) ;
iteml.Date = DateTime.Now;
iteml.userid = Convert.ToInt32(Session["userid"].ToString()) ;
DatabaseContext context = new DatabaseContext();
context.itemlists.Add(iteml);
context.SaveChanges();
}
}

C# Datatable column name changing issue

This is my first post here and I am new to programming. Right now, I am trying to changing column name in the DataTable which the data is fetch from the sql database. After I changing the column name using a foreach loop, it appears that after i change the column name of the datatable, the program crash right after I bind it to the gridview.
the error occur
Any idea what is causing the error?
C# code behind:
//custom query generator
Session["query"] = db.generate_query(parameter1, parameter2, parameter3, parameter4);
//connecting sql
SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=ISMS;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand(Session["query"].ToString(),conn);
SqlDataAdapter sdal = new SqlDataAdapter(cmd1);
//when search is needed
dt_table = new DataTable();
sdal.Fill(dt_table);
// dataTable.Columns["ExistingColumnName"].ColumnName = "regnum";
//renaming column in datatable
foreach (DataColumn dtclm in dt_table.Columns) {
dt_table.Columns[dtclm.ToString()].ColumnName = dt_table.Columns[dtclm.ToString()].ColumnName.ToString().Replace("_"," ");
}
staff_attendance_gridview.Visible = true;
staff_attendance_gridview.DataSource = dt_table;
staff_attendance_gridview.DataBind();
result_message.Text = dt_table.Rows.Count.ToString() + " rows in the table";
the aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="admin_attendance_.aspx.cs" Inherits="ISMS.admin_attendance" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!--start container box-->
<div id="container_box">
<div id="text">
<asp:Label runat="server" ID="welcome_message" /><br />
<br />
<!--search bar-->
<p>
<br />
Employee ID: <asp:TextBox runat="server" ID="employee_search" Text="" /><br />
<br />
Attendance ID: <asp:TextBox runat="server" ID="attendance_ID_text_box" Text="" /><br />
<br />
fill up both attendance ID and Employee ID and click delete to delete certain record.<br />
<br />
<asp:Button ID="search_btn" runat="server" Text="search" OnClick="search_btn_Click" />
<asp:Button ID="clock_in_or_out_btn" runat="server" Text="clock in/out" OnClick="clock_in_or_out_btn_Click" />
<asp:Button ID="delete_button" runat="server" Text="delete" OnClick="delete_button_Click" />
<br />
</p>
<!--gridview-->
<hr />
<br />
<div id="gridview">
<asp:GridView runat="server" ID="staff_attendance_gridview" OnPageIndexChanging="gridview_PageIndexChanging" AutoGenerateColumns="true" DataKeyNames="Attendance_id" >
</asp:GridView>
</div>
<!--end gridview-->
<p>
<!--validator-->
<asp:RegularExpressionValidator ID="employee_search_validator" runat="server"
ErrorMessage="Invalid searching citeria. Only exactly 8 numbers is allowed."
ControlToValidate="employee_search"
ValidationExpression="^[0-9]{8}$" /><br />
<br />
</p>
<br />
<!--hyperlink to main menu-->
<asp:Label runat="server" ID="result_message" /><br />
<a href="admin.aspx" >Main menu</a>
</div>
</div>
<!--end container box-->
</asp:Content>
Database table structure
You have an attribute in your GridView that refers to a column Attendance_id. That must match the updated name of your column Attendance id.
I've corrected your code below to properly handle IDisposable and remove overly complex bits.
Session["query"] = db.generate_query(parameter1, parameter2, parameter3, parameter4);
using(SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=ISMS;Integrated Security=True"))
{
using(SqlCommand cmd1 = new SqlCommand(Session["query"].ToString(), conn))
{
using(SqlDataAdapter sdal = new SqlDataAdapter(cmd1))
{
dt_table = new DataTable();
sdal.Fill(dt_table);
}
}
}
foreach (DataColumn column in dt_table.Columns)
{
column.ColumnName = column.ColumnName.Replace("_", " " );
}
staff_attendance_gridview.Visible = true;
staff_attendance_gridview.DataSource = dt_table;
staff_attendance_gridview.DataBind();
result_message.Text = dt_table.Rows.Count + " rows in the table";

Button inside every product

I am doing a little school project with ASP.NET, and I'm trying to get all products from the Database, show it and have "Add to card" button for every one of them. I managed to do all this, except adding the button. I have a function that gets all the products and I'm binding it with ASP Repeater. The problem is, when I try to add a button, it says that I need to use the form tag first, when I add the form tag it says it needs to have runat="server", but when I add it, it says I can't have more than one runat="server". The Repeater tag is using it also, and I'm stuck. Can anyone suggest something? Thank you!
private void bindPopularProducts()
{
String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Food", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable fFood = new DataTable();
sda.Fill(fFood);
popularFood.DataSource = fFood;
popularFood.DataBind();
}
}
}
}
and this
<asp:Repeater ID="popularFood" runat="server">
<ItemTemplate>
<div class="col-md-4">
<div><%# Eval("name") %></div>
<div><asp:Image ID="foodImage" runat="server" ImageUrl='<%# "~/images/food/" + Eval("image").ToString() %>' Visible="true" CssClass="img-responsive" /></div>
<div>
<div class="col-md-4 text-left"><%# "$"+Eval("price_small")+"/small" %></div>
<div class="col-md-8 text-right">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I'm trying to put the button inside the text-right div
Within your Repeater's ItemTemplate, add a button. In the button, set the CommandArgument to some key value that uniquely identifies the product.
<asp:Button ID="Button1" runat="server" Text="Click Me" CommandArgument='<%# Eval("Product.Key") %>' OnClick="Button1_Click" />
In your code, the event handler can use the button's CommandArgument to get the product key and execute your "Add to card" method.
protected void Button1_Click(object sender, EventArgs e)
{
string myProductKey;
// Use "myProductKey" to do something with the Product record...
myProductKey = ((Button)sender).CommandArgument;
}

How do I get the textbox value to the database within a repeater?

I have a repeater that I populate from a database:
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"SELECT CommunityName, CID, Budget FROM Donation WHERE Year = year(getdate()) ORDER BY CommunityName", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
myRep.ItemDataBound += new RepeaterItemEventHandler(myRep_ItemDataBound);
myRep.DataSource = myDataSet;
myRep.DataBind();
}
void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var textbox = e.Item.FindControl("community");
textbox.ClientIDMode = ClientIDMode.Static;
textbox.ID = "community" + (e.Item.ItemIndex + 1);
}
Repeater:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="community" Text='<%# Eval("Budget") %>' CssClass="form-control" />
</div>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
This creates 6 textboxes with labels and values, now my question is how do I detect which of these boxes belongs to the record it was initially pulled from in the database? I want to be able to modify the value in these boxes and hit a button to save them back to the database but I can't seem to wrap my head around getting them to the proper records.
Should I set the ID of the textbox to something I can parse through and match with the proper record? In the ItemDataBound?
You have to put a hidden field inside the repeater item template that takes the value from budget, and another hidden field to keep the CID value that has to be read in the post back request. Of course you need also a button and its click event handler.
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="txtBudget" Text='<%# Eval("Budget") %>' CssClass="form-control" />
<asp:HiddenField runat="server" ID="hdOriginalBudget" Value='<%# Eval("Budget") %>' />
<asp:HiddenField runat="server" ID="hdCID" Value='<%# Eval("CID") %>' />
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
In your code behind you need to loop inside the repeater to check whether the text box has been changed by comparing its value to the hidden field. After you save the budget value in the database you need to realign the hidden field value to the the new value entered by the user, otherwise you will always save that value after each post back:
protected void btn_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in myRep.Items)
{
var txtBudget = item.FindControl("txtBudget") as TextBox;
var hdOriginalBudget = item.FindControl("hdOriginalBudget") as HiddenField;
var hdCID = item.FindControl("hdCID") as HiddenField;
if (txtBudget.Text != hdOriginalBudget.Value)
{
//If you enter here means the user changed the value of the text box
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"UPDATE Donation SET Budget = #Budget WHERE CID = #CID", conn);
cmd.Parameters.Add(new SqlParameter("#Budget", int.Parse(txtBudget.Text)));
cmd.Parameters.Add(new SqlParameter("#CID", int.Parse(hdCID.Value)));
conn.Open();
cmd.ExecuteNonQuery();
}
//After you write in the database realign the values
hdOriginalBudget.Value = txtBudget.Text;
}
}
}
Take care that my code is missing the most basic validation, so if the user writes an invalid value in the textbox (for example "yyy") it breaks. So please don't put it in production as it is!

asp.net C# - DataList2 Refresh based on the value of DataList1

I am new to ASP.NET and C#. I want to refresh the 2nd DataList (DataList2) when a user clicks on the (+) sign.
Datalist1 will list all Company records with a column that has a (+) sign. If a user clicks the (+), it will expand (DataList2) below the company and list all the contact names.
Please help. Thanks!
<%# Page Language="C#" AutoEventWireup="true" CodeFile="CompanyList.aspx.cs" Inherits="_CompanyList" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link id="Link1" rel="stylesheet" runat="server" media="screen" href="/Apps/ERP/ERP_Styles.css" />
</head>
<body>
<form id="form1" runat="server">
<table style="width:100%" border="0">
<tr>
<td style="width:20%"></td>
<td style="width:60%">
<p class="PageTitle">Company List</p>
</td>
<td style="width:20%">
<asp:Button ID="myBtn" runat="server" Text="Click me"
OnClientClick="window.parent.location.href='/Apps/ERP/ASPX/UploadContact/UploadContact.aspx'; return false;" />
</td>
</tr>
</table>
<%-- ////////////////////////////////////// Start Data Row ///////////////////////////////////////// --%>
<table width="595px">
<asp:DataList BackColor="#ffffff" id="DataList1" DataSourceID="dsCompanyList" runat="server" Width="100%">
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="LinkButton1" runat="server" Text="+" CommandArgument='<%#Container.ItemIndex%>'
OnCommand="LinkButton1_Command"
></asp:LinkButton>
</td>
<td><%#Eval("Row")%></td>
<td><%#Eval("Company")%></td>
</tr>
<asp:Panel ID="pnlChildView" runat="server">
<asp:DataList ID="DataList2" runat="server" Width="100%">
<ItemTemplate>
<tr>
<td><%#Eval("FirstName")%></td>
<td><%#Eval("LastName")%></td>
</tr>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
</table>
<asp:SqlDataSource ID="dsCompanyList" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnApps %>"
SelectCommand="SELECT ROW_NUMBER() OVER (ORDER By MatchFlag ASC) AS ROW
, Company FROM (
SELECT DISTINCT(Company) AS Company, MatchFlag
--,InsertFlag, MatchFlag
FROM dbo.Import_CompanyContact icc
WHERE RefNum = #RefNum
AND MatchFlag = 2
) a "
>
<SelectParameters>
<asp:QueryStringParameter Name="RefNum" QueryStringField="RefNum" DefaultValue="0" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
The code behind .cs file
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _CompanyList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
//pass index of item in command argument
int itemIndex = Convert.ToInt32(e.CommandArgument);
//depending on your needs bind the details on demand
//or preload during ItemDataBound
Panel childViewPanel = (Panel)DataList1.Items[itemIndex].FindControl("pnlChildView");
if (childViewPanel != null)
{
//toggle visibility of childViewPanel and bind child list if panel is visible
if (childViewPanel.Visible)
{
DataList childList = (DataList)childViewPanel.FindControl("DataList2");
if (childList != null)
{
int keyValue = (int)DataList1.DataKeys[itemIndex];
//bind the list using DataList1 data key value
childList.DataSource = "SELECT FirstName, LastName FROM dbo.Import_CompanyContact WHERE Company = 'Applied Micro'"; //get data using keyValue
childList.DataBind();
}
}
}
}
}
There are a few things needed to make this work for you, but first - please consider using stored procedures or at least parameterized queries.
You are attempting to access the .DataKeys of the "parent" DataList but you never included that on your definition. In order to accurately do this, you're going to need to change your source query to include some key value (instead of just ROW_NUMBER() (not a key) and Company):
<asp:DataList BackColor="#ffffff"
id="DataList1"
DataSourceID="dsCompanyList"
runat="server"
Width="100%"
DataKeyField="YourKeyField">
Then, you'll need to alter your code-behind to set the .DataSource of your "child" DataList...and while I'm using your query, please consider using something other than dynamic SQL:
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
int itemIndex = Convert.ToInt32(e.CommandArgument);
Panel childViewPanel = (Panel)DataList1.Items[itemIndex].FindControl("pnlChildView");
if (childViewPanel != null)
{
if (childViewPanel.Visible)
{
DataList childList = (DataList)childViewPanel.FindControl("DataList2");
if (childList != null)
{
int keyValue = (int)DataList1.DataKeys[itemIndex];
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT FirstName, LastName FROM dbo.Import_CompanyContact WHERE Company = " + keyValue, con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader())
{
childList.DataSource = dr;
childList.DataBind();
}
}
}
}
}
}
}

Categories