Show Selected Columns in a different page in a Gridview - c#

Can anyone please help me i have in ASP.NET A Table called : info , with 3 columns : id,name,code
I want on a page called Default.aspx to have a checkboxlist that shows the table's Columns and when the user selects what columns he wants to see , then he presses a button to redirect him to Another Page and be shown in a Gridview (the gridview results to be show in a different page it's very important)
Page 1 :
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" BackColor="#FFFFCC" Height="165px" Width="155px">
<asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>
<br />
</asp:Panel>
</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" style="height: 26px" Text="Button" />
<br />
</form>
Code behind Page 1 :
SqlConnection con = new SqlConnection("Server=.\\SQLEXPRESS;Database = ProiectWeb; Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
loadData();
}
}
private void loadData()
{
cmd.Connection = con;
cmd.CommandText = "SELECT column_name FROM information_schema.columns WHERE table_name ='info' ORDER BY ordinal_position";
con.Open();
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
CheckBoxList1.Items.Add(reader[0].ToString());
}
}
reader.Close();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
Page 2 :
<asp:Panel ID="Panel2" runat="server" Height="302px" Width="278px">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" style="margin-left: 0px">
</asp:GridView>
</asp:Panel>
Code Behind Page 2 :
SqlConnection con = new SqlConnection("Server=.\\SQLEXPRESS;Database = ProiectWeb; Integrated Security=True");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
cmd.Connection = con;
loadGrid("SELECT * FROM info");
}
}
public void loadGrid(string query)
{
DataSet data = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(query,con);
adapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}

You need to follow, this.
In Button1_click event, get selected list of selected checkboxes and post them as query string to second page. I know querystring has length limitation and there are other way of passing values ( post data, session ..), but still if column list is less, you are good to go with this approach.
Following code will get list of selected columns, and redirect to second page.
protected void Button1_Click(object sender, EventArgs e)
{
List<string> selected = CheckBoxList1.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Text)
.ToList();
string sel = string.Join(",", selected);
Response.Redirect("Second.aspx?cols=" + sel);
}
In second page , page_load event read the querystring cols , and use Row_databound event of gridview to make rest of columns hidden except those passed in as querystring.
For this case, you can refer - GridView Hide Column by code OR Hide a GridView column by name at runtime in ASP.Net
Again, there are options to implement this, like generate dynamic SQL to get only required data and bind that to gridview. But the above seems simple one, that is why i explained in that way.

Related

How to insert multiple different textboxes to database table one by one for each row?

I have 3 different textboxes for serials. And when I click the button I want to save them for each row in database table.
Textbox1.Text="HP" ==> STOCKID
Textbox2.Text="İ5" ==> MODEL
Textbox3.Text="3" ==> QUANTITY
Textbox4.Text="11231231"; ==> SERIAL-1
Textbox5.Text="11231231"; ==> SERIAL-2
Textbox6.Text="11231231"; ==> SERIAL-2
Then Button click event.
Result should be as below.
FIRST GRIDVIEW
STOKID
MODEL
QUANTİTY
HP
I5
3
SECOND GRIDVIEW
STOKID
MODEL
SERIALS
DELETEBUTTON
HP
I5
32165161
BUTTON
HP
I5
12313223
BUTTON
HP
I5
16516516
BUTTON
When I delete from serials one bye one, the first Gridview QTY should decrease one for each serials. Is it possible?
I use store procedure during insert to data for first gridview. But for second one I don't know how to use a loop for textboxes and add to database different serials(textboxes values).
Ok, so say this markup:
We have Stokkid, model, and then have 3 optional serial num boxes
(if they are left blank - we don't add).
So, this markup:
The boxes, and add button:
<div style="float: left">
<h4>Stokid</h4>
<asp:TextBox ID="txtStokID" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px">
<h4>Model</h4>
<asp:TextBox ID="txtModel" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px">
<h4>Serial 1</h4>
<asp:TextBox ID="txtS1" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px">
<h4>Serial 2</h4>
<asp:TextBox ID="txtS2" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px">
<h4>Serial 3</h4>
<asp:TextBox ID="txtS3" runat="server"></asp:TextBox>
</div>
<div style="float: left;margin-left:20px;margin-top:20px">
<asp:Button ID="cmdSave" runat="server" Text="Save/Add" CssClass="btn"
OnClick="cmdSave_Click"
/>
</div>
<div style="clear:both" ></div>
And right below that, 2 grids, the first totals gv, and then the data we have gv.
So, this:
<h3>Counts</h3>
<asp:GridView ID="GVCounts" runat="server" CssClass="table"
width="40%" ShowHeaderWhenEmpty="True" >
</asp:GridView>
<h3>Items</h3>
<asp:GridView ID="GridView1" runat="server" CssClass="table"
width="40%" ShowHeaderWhenEmpty="True" >
</asp:GridView>
And now our code to load up the above:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
// load up "counts" grid
string strSQL =
#"SELECT Stokid, Model, count(*) as QTY FROM tblSerials
GROUP BY Stokid, Model";
GVCounts.DataSource = MyRst(strSQL);
GVCounts.DataBind();
// Load up existing data grid
strSQL =
#"SELECT Stokid, Model, Serials FROM tblSerials ORDER BY ID";
GridView1.DataSource = MyRst(strSQL);
GridView1.DataBind();
}
So, only part left is the "add new data button"
That code is this:
protected void cmdSave_Click(object sender, EventArgs e)
{
// save (add) one row for each serial number,
// if no serial - then don't add
DataTable dt = MyRst("SELECT * FROM tblSerials WHERE ID = 0");
DataRow MyAddRow = dt.NewRow();
MyAddRow["Stokid"] = txtStokID.Text;
MyAddRow["Model"] = txtModel.Text;
MyAddRow["Serials"] = txtS1.Text;
dt.Rows.Add(MyAddRow);
if (txtS2.Text != "")
{
MyAddRow = dt.NewRow();
MyAddRow["Stokid"] = txtStokID.Text;
MyAddRow["Model"] = txtModel.Text;
MyAddRow["Serials"] = txtS2.Text;
dt.Rows.Add(MyAddRow);
}
if (txtS3.Text != "")
{
MyAddRow = dt.NewRow();
MyAddRow["Stokid"] = txtStokID.Text;
MyAddRow["Model"] = txtModel.Text;
MyAddRow["Serials"] = txtS3.Text;
dt.Rows.Add(MyAddRow);
}
// send/save all rows to database
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST5))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblSerials", conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(dt);
}
}
// Update counts and display
LoadData();
}
so, the result is now this:
Now, we do probably want to setup a delete button.
so, that means our "cheat" life and easy GV of data?
Well, we have to give it a bit more effort, love and care.
We need the database PK id, and we want that delete button.
And since the delete button can be a danger, then it should confirm.
So, we have to update our GV a bit, bite the bullet and use some templating. but, it is not much.
And lets use a boot-strap icon - they should be part of any most recent project by defualt. But BE warned, after boottrap 4, the later versions (due to some copyright/lawsuit, bootstrap does not include the glyph-icons).
Anyway, I COULD use a plain jane asp.net button in the gv for delete, but lets use standard html button - I ONLY use the html one, since I wanted the cute icon. Probably better for you to use a image button.
(code is much the same either way).
So, our 2nd gv now looks like this:
<h3>Items</h3>
<asp:GridView ID="GridView1" runat="server" CssClass="table table-hover"
width="40%" ShowHeaderWhenEmpty="True" DataKeyNames="ID"
AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="STOKID" HeaderText="STOKID" />
<asp:BoundField DataField="MODEL" HeaderText="MODEL" />
<asp:BoundField DataField="serials" HeaderText="serials" />
<asp:TemplateField HeaderText="Delete" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<button id="cmdDelete" runat="server" class="btn"
onclick="if (!confirm('Delete')) return false;"
onserverclick="cmdDel_ServerClick" >
<span aria-hidden="true" class="glyphicon glyphicon-trash"></span>
</button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code to load up this gv is now:
void LoadData()
{
// load up "counts" grid
string strSQL =
#"SELECT Stokid, Model, count(*) as QTY FROM tblSerials
GROUP BY Stokid, Model";
GVCounts.DataSource = MyRst(strSQL);
GVCounts.DataBind();
// Load up existing data grid
strSQL = #"SELECT * FROM tblSerials ORDER BY ID";
GridView1.DataSource = MyRst(strSQL);
GridView1.DataBind();
}
And our delete code is this:
protected void cmdDel_ServerClick(object sender, EventArgs e)
{
HtmlButton btn = (HtmlButton)sender;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
string strSQL = "DELETE FROM tblSerial WHERE ID = {PKID}";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST5))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
// update count and items gv
LoadData();
}
So, now we see, get this for a delete:
Edit2: The Myrst routine
In a few places in above, I also used this helper routine, since I get VERY tired VERY fast having to write code each and every time I want some data, so, I wrote and use this routine:
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST5))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
It handy for filling out a gridview, dropdown list etc.

SQL Select ID from automatically generated rows with C#

Basically whenever i would press a button on my website it would generate some kind of report with the ID and other information. What am trying to do is change one column of the table with SQL statements. I managed to change it but the code changes the column for all the IDs. What am trying to do is change column according to ID, but am still new to C# and SQL so i'm not sure how to get the automatic generated row. Just to highlight that i'm using a button in a gridview to change the value in the column. Below is what i tried:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string order = Request.QueryString["id"];
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["RCManiaConnectionString"].ConnectionString;
con.Open();
if (e.CommandName == "received")
{
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "UPDATE [Orders] SET Status = 'Received' WHERE [ID] ='" + order + "'";
SqlDataReader data = com.ExecuteReader();
}
}
Using DataKeyNames property of grid view you can pass each record's primary key value, assign the same to the button of the record under CommandArgument. The below code is working code. You can try the same.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" OnRowDataBound="GridView1_RowCommand">
<EmptyDataTemplate>
No Data Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="Update" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="btnUpdate" runat="server" CausesValidation="false" OnClick="btnUpdate_Click" CommandName="Select" ImageUrl="~/Contents/Images/classicPencil.svg" Width="20" Height="20" Text="View" CommandArgument='<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//Using Direct button click event
protected void btnUpdate_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = sender as ImageButton;
int ID = Convert.ToInt32(btn.CommandArgument);
//Your code of update data process
}
//Using grid row command event.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument.ToString());
//Your code of update data process
}

I can't get the delete link button on gridview to work

I am currently creating an asp.net web app in C# using Visual Studio. I have a gridview that displays data from a database table and I have added the datasource manually in my .cs page as I have converted the childrens DOB into age, thus enabling me to filter the gridview with a dropdown list of age groups. This all works fine, the only issue i'm having is getting the delete link button to work. I need it to completely delete the child from the database table if clicked.
I began by going to the gridview in design mode, Add new column --> Button field (button type 'link', command name 'delete') and then adding the following code in my .cs page:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from children where " +
"childID=#childID";
cmd.Parameters.Add("#childID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = source;
GridView1.DataBind();
}
When I run the page and click delete next to any of the children, I get the following error:
I will include the full code from my .cs page as well as my source code. Can someone help me figure out why I am getting the error and why the delete buttons wont delete without issue? Thanks in advance.
FULL .CS CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace Coursework
{
public partial class Testy1 : System.Web.UI.Page
{
//create a datasource
SqlDataSource source = new SqlDataSource();
protected void Page_Load(object sender, EventArgs e)
{
//always set some defaults for the sqldatasource
source.ID = "source1";
source.ConnectionString = ConfigurationManager.ConnectionStrings["newregDBConnectionString"].ConnectionStr‌​ing;
source.SelectCommand = "SELECT firstname, dob, DATEDIFF(hour, dob, GETDATE()) / 8766 AS age FROM children ORDER BY age";
if (!IsPostBack)
{
//bind the grid
GridView1.DataSource = source;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//the new database query, now with where clause
source.SelectCommand = "SELECT firstname, dob, DATEDIFF(hour, dob, GETDATE()) / 8766 AS age FROM children WHERE (DATEDIFF(hour, dob, GETDATE()) / 8766 BETWEEN #start AND #end) ORDER BY age";
//get the end age from the dropdown and cast as int
int end = Convert.ToInt32(DropDownList1.SelectedValue);
//get the start int for the filter
int start = end - 2;
//if the filter is resetted, make sure the query returns all ages
if (end == 5)
{
start = 5;
end = 99;
}
//replace the parameters in the query
source.SelectParameters.Add("start", start.ToString());
source.SelectParameters.Add("end", end.ToString());
//rebind the grid
GridView1.DataSource = source;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from children where " +
"childID=#childID";
cmd.Parameters.Add("#childID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = source;
GridView1.DataBind();
}
}
SOURCE CODE:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Testy1.aspx.cs" Inherits="Coursework.Testy1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<p></p>
<p></p>
<p></p>
<p></p>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Filter age" Value="5"></asp:ListItem>
<asp:ListItem Text="5 - 7" Value="7"></asp:ListItem>
<asp:ListItem Text="8 - 10" Value="10"></asp:ListItem>
<asp:ListItem Text="11 - 13" Value="13"></asp:ListItem>
<asp:ListItem Text="14 - 16" Value="16"></asp:ListItem>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDeleting="GridView1_RowDeleting" >
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("firstname") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DOB">
<ItemTemplate>
<%# Convert.ToDateTime(Eval("dob")).ToString("d MMMM yyyy") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%# Eval("age") %>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="Delete" Text="Delete" />
</Columns>
</asp:GridView>
</asp:Content>
The sender is the GridView in RowDeleting, not the button, so your cast fails.
If you would specify the DataKeyNames you could use the GridView's DataKeys property:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
DataKeyNames = "childID"
OnRowDeleting="GridView1_RowDeleting" >
Codebehind:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string childId = GridView1.DataKeys[e.RowIndex].Value.ToString();
string deleteSql = #"DELETE FROM Children
WHERE childID = #childID;";
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["newregDBConnectionString"].ConnectionStr‌​ing))
using(var cmd = new SqlCommand(deleteSql, con))
{
cmd.Parameters.Add("#childID", SqlDbType.VarChar).Value = childId;
con.Open();
int deleted = cmd.ExecuteNonQuery();
}
GridView1.DataSource = GetDataSource(); // provide a method that returns it
GridView1.DataBind();
}
Well, you are handling GridView's Deleting event, not button's click. So your sender is actually a GridView control, you should not cast it to LinkButton.
Besides, you did not assign CommandArgument. Should be something like that:
<asp:ButtonField CommandName="Delete" Text="Delete" CommandArgument='<%# Eval("childID") %>' />
But even if you did, this is not going to help as CommandArgument is not passed along with Delete even args. Thus, you have two options.
First is to switch to handling RowCommand event:
OnRowDeleting="GridView1_RowCommand"
In there you need to check that command is actually a delete one, and use command arg to delete:
if (e.CommandName == "Delete")
{
// parse e.CommandArgument and delete
}
Second is to define primary keys for the rows.
DataKeyNames="childID"
This is going to be available via event args of Deleting event:
e.Keys
You do not need to set CommandArgument at all in this case.

automatically update label when entering content in textbox asp.net

I have a textbox and a label in ASP.NET and i want to automatically update the label with a value from database that is fetched using the content entered in textbox. This should be done dynamically when the text is changed in textbox and if a match if found in database, the corresponding value should be displayed in the label field (without page refresh). In this case I will enter employee ID in textbox and employee name should be displayed in label. I am using the following code,
<asp:ScriptManager ID="script_manager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="update_name" runat="server">
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" AutoPostBack="true" OnTextChanged="text_empID_TextChanged" runat="server"></asp:TextBox>
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
The code behind is as follows,
protected void text_empID_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select EmployeeName from EmployeeTable where EmployeeID=#id", con);
cmd.Parameters.AddWithValue("#id", text_empID.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
label_empName.Text = dt.Rows[0]["EmployeeName"].ToString();
}
}
But this is not working. Also after entering a value in textbox and if i click outside the box, the text inside disappears. Is there any other way to do this? or am i doing something wrong here?
I would suggest that you should add a button because the text_changed event only fires when the text-box blurs (loses focus).
That's a very weird behaviour and most users are not used to it and will not expect it.
<ContentTemplate>
<asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" runat="server></asp:TextBox>
<asp:button id="btnSearch" runat="server" OnClick="text_empID_TextChanged" />
<asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>
In any case, have you added a breakpoint? does the event fire? do you get any data back in the DataTable?
EDIT
After your last comment I am convinced that you are clearing the contents of the label on page load.
please, make sure that you only do that in the following context:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
label_empName.Text = "";
}
}

Bound value to a hiddenfield inside a datalist is not specific to an item

I'm a beginner for asp.net(C#) and I'm working on a social networking application. I've stuck on the status update and comment section. I want that when page is loaded all the threads(status') should have their IDs in their hiddenfields inside the datalist as I've created an ItemTemplate for status and assigned Thread_ID to the hiddenfield. But the problem is that hiddenfield is not having different values for the different Items. I don't know where I'm doing the mistake. Please help me.
Here is the code for datalist:
<asp:DataList ID="DataListStatus" runat="server" RepeatColumns="1"
onitemdatabound="DataListStatus_ItemDataBound"
onitemcommand="DataListStatus_ItemCommand">
<ItemTemplate>
<table width="550px">
<tr><asp:HiddenField ID="HFieldThreadID" Value='<%#Eval("Thread_ID") %>' runat="server" />
<td style="vertical-align:top; width:50px;" align="left" rowspan="3"><a href='UserProfile.aspx?loginid=<%#Eval("RegID")%>' ><img alt="Propic" src="../Images/ProPic.jpg" width="50px" height="50px" /></a></td>
<td style="vertical-align:top; width:250px;" align="left"><a href='UserProfile.aspx?loginid=<%#Eval("RegID")%>' ><%#Eval("RegID")%></a></td>
<td style="vertical-align:top; width:250px;" align="right"><%#Eval("St_Time") %></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
And here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
da.SelectCommand = new SqlCommand("SELECT * FROM Status where RegID='" + Session["user"].ToString() + "'", con);
con.Open();
da.Fill(ds, "status");
con.Close();
DataListStatus.DataSource = ds.Tables["status"];
DataListStatus.DataBind();
}
}
And here I'm using the hiddenfield's value in the inner datalist for the comments:
protected void DataListStatus_ItemDataBound(object sender, DataListItemEventArgs e)
{
da.SelectCommand = new SqlCommand("SELECT * FROM Comment WHERE Thread_ID='" + ((HiddenField)e.Item.FindControl("HFieldThreadID")).Value + "'", con);
con.Open();
da.Fill(ds, "cmts");
con.Close();
((DataList)e.Item.FindControl("DataListCmt")).DataSource = ds.Tables["cmts"];
((DataList)e.Item.FindControl("DataListCmt")).DataBind();
}
One thing I notice in ItemDataBound is you want to make sure e.Item is of type Item or AlternatingItem before searching and binding controls inside item.
NOTE: please use Parameterized Query to avoid SQL injection.
protected void DataListStatus_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
da.SelectCommand = new SqlCommand("SELECT * FROM Comment WHERE Thread_ID='" + ((HiddenField)e.Item.FindControl("HFieldThreadID")).Value + "'", con);
con.Open();
da.Fill(ds, "cmts");
con.Close();
var dataList = (DataList)e.Item.FindControl("DataListCmt");
dataList.DataSource = ds.Tables["cmts"];
dataList.DataBind();
}
}
Don't use hidden field . Because the page load time this hidden-field field was cleared .So please use label control and set visible="false" in the label control.
And Must the DataList binding method call Inside of !IsPostBack in pageload event

Categories