In asp.net web application I get this error when populating datalist from database.
In design page I have some labels inside an item-template tag, when I try to access these labels by FindControl it gives the error:
Object reference not set to an instance of object
here is my code:
Products.aspx.cs:
public partial class Products : System.Web.UI.Page
{
Product product;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
DataList1.DataBind();
product = this.getProducts();
Label TitleLabel = (Label)DataList1.FindControl("TitleLabel");
TitleLabel.Text = product.Name;
Label DescLabel = (Label)DataList1.FindControl("DescLabel");
DescLabel.Text = product.LongDescription;
Label PriceLabel = (Label)DataList1.FindControl("PriceLabel");
PriceLabel.Text = product.UnitPrice.ToString();
ImageButton PImage = (ImageButton)DataList1.FindControl("ImageButton1");
PImage.ImageUrl = "images/"+product.ImageFile;
}
private Product getProducts()
{
Product p = new Product();
DataView productsTable = (DataView)
SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView row in productsTable)
{
p.ProductID = row["P_Id"].ToString();
p.Name = row["Title"].ToString();
p.ShortDescription = row["Desc"].ToString();
p.LongDescription = row["Desc_full"].ToString();
p.UnitPrice = Convert.ToDecimal(row["Price"]);
p.ImageFile = row["imageurl"].ToString();
}
return p;
}
}
Products.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Products.aspx.cs" Inherits="ECProject.Products" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" DataKeyField="P_Id"
DataSourceID="SqlDataSource1" RepeatColumns="4"
RepeatDirection="Horizontal" CellPadding="4" ForeColor="#333333" >
<AlternatingItemStyle BackColor="White" ForeColor="#284775" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#F7F6F3" ForeColor="#333333" />
<ItemTemplate >
<asp:ImageButton ID="ImageButton1" runat="server" Height = "200px"/>
<br />
Title:
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
<br />
Brand:
<asp:Label ID="DescLabel" runat="server" Text='<%# Eval("Desc") %>' />
<br />
Available:
<asp:Label ID="Is_ActiveLabel" runat="server" Text='<%# Eval("Is_Active") %>' />
<br />
Price:
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price") %>' />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ECDB.mdf;Integrated Security=True;User Instance=True"
ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [Product]">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
Error:
Line 25:
Line 26: Label TitleLabel = (Label)DataList1.FindControl("TitleLabel");
Line 27: TitleLabel.Text = product.Name;
Line 28:
Line 29:
Please help, how to get rid of this error ?
The list usually contains more than one item, so your logic is flawed. What you can do it handle the ItemDataBound event of the list by adding such line in your Page_Load:
DataList1.ItemDataBound += new DataListItemEventHandler(DataList1_ItemDataBound);
And have such method:
void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label TitleLabel = (Label)e.Item.FindControl("TitleLabel");
TitleLabel.Text = "changed by code";
}
}
To customize your individual DataList items, you need to do it in the ItemDataBound event. Check out this tutorial for more details.
However, it looks like you are approaching your task in an incorrect manner. Bottom line is that you need to bind your DataSource to a collection of items, and you are trying to feed it items one-by-one. Let me know if I misunderstood you and you do need to bind an individual Product to your DataList customizing its appearance at bind time.
I think your lable put in other object same as panel. you should find the real name of your lable in html code, so the best way is putting a mistake error in you script code as a result when your solution is runnig it will stop and you can find the real name of your lable control. Then use below code :
Label TitleLabel = (Label)DataList1.FindControl("REAL NAME OF LABEL CONTROL");
I hope it can help you.
Related
Actually i am trying to redirect command argument of a button present in a data list to another page. I am using Request.QueryString method to access the command argument on another page with the help of command name of the button. Please help me with it...
this is code of button present inside Data List
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
this is code present in DataList Item command function
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
this is the onclick function code
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("content.aspx");
}
this is the code on another page(content.aspx)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
this is entire datalist code
<asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" Height="657px" RepeatColumns="4" RepeatDirection="Horizontal" Width="1248px" OnItemCommand="DataList1_ItemCommand" OnItemDataBound="DataList1_ItemDataBound">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<ItemStyle ForeColor="#000066" />
<ItemTemplate>
<table class="auto-style2">
<tr>
<td style="text-align: center">
<asp:Label ID="Label2" runat="server" Text='<%# Eval("name") %>'></asp:Label>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Id") %>' Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Image ID="Image2" runat="server" Height="250px" ImageUrl='<%# Eval("image") %>' Width="250px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<br />
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="addtofav" CommandArgument='<%# Eval("id")%>' Height="30px" Width="20px" />
</td>
</tr>
<tr>
<td style="text-align: center">
<asp:Button ID="Button1" runat="server" Text="Read" CommandArgument='<%# Eval("id")%>' OnClick="Button1_Click" CommandName="content"/>
</td>
</tr>
</table
<br />
<br />
</ItemTemplate>
<SelectedItemStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
it does redirect to another page(content.aspx) but the label does not show the querystring text.
Try updating the DataList1_ItemCommand event to this:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content=" +e.CommandArgument.ToString());
}
}
also make sure you are checking IsPostBack in Page_Load method of this page code behind.
Yes i got the desired output. Actually i was also using another button to redirect to a diiferent page in DataList1_ItemCommand function. So i just needed to seperate the Response.redirects of the 2 buttons by putting them in if loop.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "content")
{
Response.Redirect("content.aspx?content="+e.CommandArgument.ToString());
}
if (e.CommandName == "addtofav")
{
Response.Redirect("sortbyAZ.aspx?addtofav=" + e.CommandArgument.ToString());
}
}
Thanks You everybody for helping me out with this one
I think you are not casting the Request.QueryString["content"] to string format, try this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String id = Request.QueryString["content"];
Label1.Text = id;
}
}
You can find all information you need in this tutorial. from #microsoft msdn
Best of luck
<%# Page Language="C#" AutoEventWireup="True" %>
<%# Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>DataList Select Example</title>
<script runat="server">
ICollection CreateDataSource()
{
// Create sample data for the DataList control.
DataTable dt = new DataTable();
DataRow dr;
// Define the columns of the table.
dt.Columns.Add(new DataColumn("Item", typeof(Int32)));
dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));
dt.Columns.Add(new DataColumn("Price", typeof(double)));
// Populate the table with sample values.
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i * 2;
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
// Load sample data only once, when the page is first loaded.
if (!IsPostBack)
{
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
}
void Item_Command(Object sender, DataListCommandEventArgs e)
{
// Set the SelectedIndex property to select an item in the DataList.
ItemsList.SelectedIndex = e.Item.ItemIndex;
// Rebind the data source to the DataList to refresh the control.
ItemsList.DataSource = CreateDataSource();
ItemsList.DataBind();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h3>DataList Select Example</h3>
Click <b>Select</b> to select an item.
<br /><br />
<asp:DataList id="ItemsList"
GridLines="Both"
CellPadding="3"
CellSpacing="0"
OnItemCommand="Item_Command"
runat="server">
<HeaderStyle BackColor="#aaaadd">
</HeaderStyle>
<AlternatingItemStyle BackColor="Gainsboro">
</AlternatingItemStyle>
<SelectedItemStyle BackColor="Yellow">
</SelectedItemStyle>
<HeaderTemplate>
Items
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton id="SelectButton"
Text="Select"
CommandName="Select"
runat="server"/>
Item <%# DataBinder.Eval(Container.DataItem, "Item") %>
</ItemTemplate>
<SelectedItemTemplate>
Item:
<asp:Label id="ItemLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Item") %>'
runat="server"/>
<br />
Quantity:
<asp:Label id="QtyLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Qty") %>'
runat="server"/>
<br />
Price:
<asp:Label id="PriceLabel"
Text='<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}")
%>'
runat="server"/>
</SelectedItemTemplate>
</asp:DataList>
</form>
</body>
</html>
By the way I think you don't need define Button Click event. Already defined path with variable. Just convert button to Link Button and remove Button Click Event
I want to grab the selected value from the DropDownLists in my DataGrid when a submit button is clicked, but they always return the first option in the dropdown (approve). How can I get the selected value when using static dropdown items like this?
.aspx code:
<!-- several BoundColumns were here -->
<asp:TemplateColumn HeaderText="Actions">
<HeaderStyle CssClass="ProfDataGridHeader" BorderStyle="Solid" BorderWidth="1"></HeaderStyle>
<ItemStyle Width="45%" CssClass="ProfDataGridRow" BorderStyle="Solid" BorderWidth="1"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="ddlApprovalStatus" AppendDataBoundItems="True" runat="server" Width="150px" EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="approve" Text="Approve"></asp:ListItem>
<asp:ListItem Value="reject" Text="Reject"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" CssClass="ally-btn" OnClick="btnSubmit_Click" />
.aspx.cs code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
DropDownList DDLP;
string acceptStatus;
debugLabel.Text = "";
for (int i = 0; i < dgApprovals.Items.Count; i++)
{
DDLP = (DropDownList)dgApprovals.Items[i].FindControl("ddlApprovalStatus");
acceptStatus = DDLP.SelectedValue;
debugLabel.Text += acceptStatus + ", ";
}
}
The debugLabel.Text always ends up being "accept, accept, accept..." even when the DropDownLists have "Reject" selected.
Reproduced and fixed your problem by handling post-back events.
default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace DropdownClicks
{
public partial class WebForm1 : System.Web.UI.Page
{
static List<string> itemsToInsert = new List<string> { "first", "second", "third" };
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//only do this binding on page load, otherwise you'll "reset" the grid every time there is a postBack.
mydg.DataSource = itemsToInsert;
mydg.DataBind();
}
}
protected void Unnamed_Click(object sender, EventArgs e)
{
DropDownList DDLP;
string acceptStatus;
string retVal = "";
for (int i = 0; i < mydg.Items.Count; i++)
{
DDLP = (DropDownList)mydg.Items[i].FindControl("ddlApprovalStatus");
acceptStatus = DDLP.SelectedValue;
retVal += acceptStatus + ", ";
}
lbl_1.Text = retVal;
}
}
}
default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DropdownClicks.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label Text="text" runat="server" ID="lbl_1" />
<asp:DataGrid runat="server" ID="mydg" EnableViewState="true">
<Columns>
<asp:TemplateColumn HeaderText="Actions">
<HeaderStyle CssClass="ProfDataGridHeader" BorderStyle="Solid" BorderWidth="1"></HeaderStyle>
<ItemStyle Width="45%" CssClass="ProfDataGridRow" BorderStyle="Solid" BorderWidth="1"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="ddlApprovalStatus" AppendDataBoundItems="True" runat="server" Width="150px" EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="approve" Text="Approve"></asp:ListItem>
<asp:ListItem Value="reject" Text="Reject"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Button Text="click me" runat="server" OnClick="Unnamed_Click" EnableViewState="true" />
</div>
</form>
</body>
</html>
I gave my "LabelButtons" a value which would be the "ID" for them and it outputs the text name so people see "product1", "product2" etc... but its really defined by the "ID" I need to take that "ID" when the button is clicked and output on my GridView the data that corresponds with the ID Value. How do I make it that when I click on button it will populate the gridview to give me the information I am looking for? I am sorry if this is not clear enough I will give more detail if needed. Also, I have my hiddenfield trying to hold the value for the data of the button click and it always stays null instead of taking the value of the button click id.
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.Data.SqlClient;
using TropicalServer.BAL;
namespace TropicalServer.UI
{
public partial class Products : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
DataSet dsID = new BALGetItems().GetItemTypeData();
rptrProductCategories.DataSource = dsID;
rptrProductCategories.DataBind();
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
HiddenField hf = (HiddenField)e.Item.FindControl("hf");
LinkButton cat = (LinkButton)e.Item.FindControl("lbPC");
hf.Value = Convert.ToString(e.CommandArgument);
PopulateGrid(new BALGetItems().GetItemData(Convert.ToInt32(hf.Value)));
}
private void PopulateGrid(DataSet ds)
{
int value = 0;
if (Cache["Data"] == null)
{
DataSet dsID = new BALGetItems().GetItemData(value);
Cache["Data"] = dsID;
gvPC.DataSource = dsID;
gvPC.DataBind();
}
else
{
gvPC.DataSource = (DataSet)Cache["Data"];
gvPC.DataBind();
}
}
}
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage/TropicalServer.Master" AutoEventWireup="true" CodeBehind="Products.aspx.cs" Inherits="TropicalServer.UI.Products" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<! DOCTYPE html>`enter code here`
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2">
<link type="text/css" rel="stylesheet" href="~/AppThemes/TropicalStyles/Products.css" />
<title>ServerLogin</title>
</head>
<body>
<table>
<tr>
<td>
<div>
<asp:Label ID="lblPC" class="productCategories" runat="server" Text="Product Categories"></asp:Label>
</div>
<div >
<asp:Repeater ID="rptrProductCategories" runat="server" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lbPC" runat="server" CommandArgument='<%#DataBinder.Eval(Container,"DataItem.ItemTypeID") %>' Text='<%#DataBinder.Eval(Container,"DataItem.ItemTypeDescription")%>'/><br />
</ItemTemplate>
</asp:Repeater>
</div>
</td>
<td>
<div class="dataGrid">
<asp:GridView ID="gvPC" runat="server" PagerSettings-PageButtonCount="5" AutoGenerateColumns="False" PageSize="5" AllowPaging="True" EnableSortingAndPagingCallbacks="True" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" GridLines="Horizontal">
<Columns>
<asp:BoundField HeaderText="ItemNumber" DataField="ItemNumber"/>
<asp:BoundField HeaderText="ItemDescription" DataField="ItemDescription" />
<asp:BoundField HeaderText="Pre-Price" DataField="PrePrice" />
<asp:BoundField HeaderText="Size" DataField="ItemUnits" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerSettings PageButtonCount="5"></PagerSettings>
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
</asp:GridView>
<asp:HiddenField ID="hf" runat="server"/>
</div>
</td>
</tr>
</table>
</body>
</html>
</asp:Content>
First, your LinkButton needs an OnClick event.
<asp:LinkButton ID="lbPC" runat="server"
CommandArgument='<%#DataBinder.Eval(Container,"DataItem.ItemTypeID") %>'
Text='<%#DataBinder.Eval(Container,"DataItem.ItemTypeDescription")%>'
OnClick="lbPC_Click"></asp:LinkButton>
Then in your click event, grab the ID, retrieve the data for your GridView, then bind the GridView.
protected void lbPC_Click(object sender, EventArgs e)
{
LinkButton lbPC = (LinkButton)sender;
int id = int.Parse(lbPC.CommandArgument)
//If for some reason you do need to hold the ID value in your hiddenfield,
//just call it as is. There is no need for FindControl() since it is
//outside of both your Repeater and your GridView.
hf.Value = id.ToString();
gvPC.DataSource = YourDataRetrievalMethod(id);
gvPC.DataBind();
}
I'm trying to build a dynamic nested collapsable gridview for a project in college.
I read this article which helped me a bit, but I'm still stuck.
the two relevant tables in my sql server are: member which contains info including id (primary key), and history table that is used to store history details about calls made with foreign key id that points to the member table. (each history row gets an int by identity-history_num).
I'd like that by a given id the grid will list all the history records which will be expendable to show the content field of the history table.
I did some tests and managed to get it to work, but not dynamic. I guess I need to create the gridview dynamically as well.
here is my aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script type="text/javascript">
function showNestedGridView(obj) {
var nestedGridView = document.getElementById(obj);
var imageID = document.getElementById('image' + obj);
if (nestedGridView.style.display == "none") {
nestedGridView.style.display = "inline";
imageID.src = "minus.png";
} else {
nestedGridView.style.display = "none";
imageID.src = "plus.png";
}
}
</script>
<body>
<form id="form1" runat="server">
<div id='div1' runat="server">
<asp:GridView ID="gridViewMaster" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" DataKeyNames="id"
ForeColor="Black" GridLines="None"
onrowdatabound="gridViewMaster_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:showNestedGridView('customerID-<%# Eval("id") %>');">
<img id="imagecustomerID-<%# Eval("history_num") %>" alt="Click to show/hide orders" border="0" src="plus.png" />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="history_num" HeaderText="history_id" ReadOnly="True"
SortExpression="Member-ID" />
<asp:BoundField DataField="h_date" HeaderText="History-Date"
SortExpression="Member-Name" />
<asp:BoundField DataField="topic" HeaderText="History-topic"
SortExpression="Member-Name" />
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="customerID-<%# Eval("history_num") %>" style="display:none;position:relative;left:25px;" >
<asp:GridView ID="nestedGridView" runat="server" AutoGenerateColumns="False"
DataKeyNames="id">
<RowStyle VerticalAlign="Top" BackColor="White" ForeColor="#330099" />
<Columns>
<asp:BoundField DataField="content" HeaderText="content"
SortExpression="OrderDate" />
</Columns>
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%-- <asp:sqldatasource ID="Sqldatasource1" runat="server"
ConnectionString="<%$ ConnectionStrings:igroup20_test2ConnectionString %>"
SelectCommand="select id, h_date, topic from history where id='038191904'"></asp:sqldatasource>--%>
</div>
</form>
</body>
</html>
and this is the code behind for now:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource sqlDS = new SqlDataSource();
sqlDS.ID = "sqlDS";
sqlDS.ConnectionString = "igroup20_test2ConnectionString";
sqlDS.SelectCommand = "select history_num, h_date, topic from history where id='038191904'";
div1.Controls.Add(sqlDS);
gridViewMaster.DataSource = sqlDS;
gridViewMaster.DataBind();
}
protected void gridViewMaster_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string his_num = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "history_num"));
GridView gridViewNested = (GridView)e.Row.FindControl("nestedGridView");
SqlDataSource sqlDataSourceNestedGrid = new SqlDataSource();
sqlDataSourceNestedGrid.ConnectionString = ConfigurationManager.ConnectionStrings["igroup20_test2ConnectionString"].ConnectionString;
sqlDataSourceNestedGrid.SelectCommand = "SELECT content from history where history_num='" + his_num + "'";
gridViewNested.DataSource = sqlDataSourceNestedGrid;
gridViewNested.DataBind();
}
}
}
history table fields are:
history_num
id
h_date
topic
content
When I click the button the information doesn't load into my table.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="frmManageUsers.aspx.cs" Inherits="frmManageUsers" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/images/CoolBiz_Productions_logo.JPG" PostBackUrl="~/frmMain.aspx" />
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [UserID], [UserName], [UserPassword], [SecurityLevel] FROM [tblUserLogin]">
</asp:SqlDataSource>
</div>
<div align="center">
<asp:Label ID="Label1" runat="server" Text="Manage Users"></asp:Label>
<p>
<asp:Label ID="Label2" runat="server" Text="User Name:"></asp:Label>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</p>
<p>
<asp:Label ID="Label3" runat="server" Text="Password:"></asp:Label>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</p>
<p>
<asp:Label ID="Label4" runat="server" Text="Security Level:"></asp:Label>
<asp:DropDownList ID="drpdwnlstSecurityLevel" runat="server"
onselectedindexchanged="drpdwnlstSecurityLevel_SelectedIndexChanged">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>U</asp:ListItem>
</asp:DropDownList>
</p>
<p>
<asp:Button ID="btnAddUser" runat="server" Text="Add User"
onclick="btnAddUser_Click1" />
</p>
<p>
<asp:Label ID="lblError" runat="server"></asp:Label>
</p>
</div>
<p>
</p>
<div align="center">
<asp:GridView ID="tblUserLogin" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" InsertVisible="False"
SortExpression="UserID"></asp:BoundField>
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName"></asp:BoundField>
<asp:BoundField DataField="UserPassword" HeaderText="UserPassword"
SortExpression="UserPassword"></asp:BoundField>
<asp:BoundField DataField="SecurityLevel" HeaderText="SecurityLevel"
SortExpression="SecurityLevel"></asp:BoundField>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
Here is my code for frmManageUsers
public partial class frmManageUsers : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAddUser_Click1(object sender, EventArgs e)
{
//string userName, userPassword;
if (txtUserName.Text == "" || txtUserName.Text == null)
{
lblError.Text = ("User Name may not be empty");
lblError.ForeColor = System.Drawing.Color.Red;
return;
}
// else
// userName = (txtUserName.Text);
if (txtPassword.Text == "" || txtPassword.Text == null)
{
lblError.Text = ("Password may not be empty");
lblError.ForeColor = System.Drawing.Color.Red;
return;
}
//else
// userPassword = (txtPassword.Text);
Session["UserName"] = txtUserName.Text;
Session["Password"] = txtPassword.Text;
Session["SecurityLevel"] = drpdwnlstSecurityLevel.SelectedValue;
Server.Transfer("frmManageUsers.aspx");
//Server.Transfer("grdUserLogin");
}
protected void drpdwnlstSecurityLevel_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You're SQL DataSource is tied to your DATAGRID control only. I don't see where in your btnAddUser_Click1 event handler you are making any calls to insert the record into the database. You will need to add this missing logic as the existing controls aren't wired up to do this. You have a code gap. You're going to need to perform something close to the following. This is just a sample as I pulled it out of one of my data access layers and modified it for viewing purposes.
string _connectionString = string.Empty;
SqlCommand sqlCommand = new SqlCommand();
SqlConnection sqlConnection = new SqlConnection();
._connectionString = config["connectionString"];
sqlConnection.ConnectionString = "<your connection string>";
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.StoredProcedure;
//add your parameters here
sqlCommand.Parameters.Add("#ParameterNameWithinProcedure", <your value goes here>);
sqlCommand.Parameters.Add("#ParameterNameWithinProcedure", <your value goes here>);
sqlCommand.Parameters.Add("#ParameterNameWithinProcedure", <your value goes here>);
//Repeat for each parameter in your record.
int returnVal = 0;
sqlCommand.CommandText = "< insert record stored procedure name"
try
{
sqlConnection.Open();
using (sqlCommand)
{
returnVal = sqlCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//possibly put some logging inforaation here
}
finally
{
sqlConnection.Close();
}
PS. In your if statements such as:
if (txtUserName.Text == "" || txtUserName.Text == null){//....}
Try using
if(String.IsNullOrEmpty(txtUserName.Text)){//...}
It's a nifty little method that reduces code.