Listview databind confusion - c#

I currenty have a stored procedure that I am running and hoping to bind the data from the sp with my list view. However, I am unsure of how to go upon doing this.
Here is my current code. I was thinking it was similar to databinding a gridview but got lost doing it.
HTML
<asp:ListView runat="server">
<LayoutTemplate>
<table>
<tr style="background-color:green">
<th><asp:LinkButton ID="lnkid" runat="server">Role ID</asp:LinkButton></th>
<th><asp:LinkButton ID="lnkdesc" runat="server">Role Description</asp:LinkButton></th>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:Label runat="server" ID="lblroleid">Role ID</asp:Label></td>
<td><asp:Label runat="server" ID="lblroledesc">Role Desc></asp:Label></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color:Aqua">
<td><asp:Label runat="server" ID="lblroleid">Role ID</asp:Label></td>
<td><asp:Label runat="server" ID="lblroledesc">Role Desc</asp:Label></td>
</tr>
</AlternatingItemTemplate>
</asp:ListView>
c#
protected void roles()
{
txtSearch.Focus();
string[] queryvalue = txtSearch.Text.Split(' ');
SqlConnection myconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Rollup2ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "USP_GET_USER_ROLES";
cmd.Connection = myconn;
cmd.Parameters.Add("#NUID", SqlDbType.VarChar).Value = queryvalue[0].ToString();
myconn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
myconn.Close();
myconn.Dispose();
}

This should help you out
ASP.NET Populate ListView with Stored Procedure
<asp:SqlDataSource ID="sdsYourData" Runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="Server=(local);Database=Northwind;Integrated Security=SSPI;"
SelectCommand="dbo.YourStoredProcName"
<SelectParameters>
<asp:Parameter Name="Param1" Type="String" />>
</SelectParameters>
</asp:SqlDataSource>

Related

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'DEPARTMENT_NAME' [duplicate]

This question already has answers here:
DataBinding: 'System.Data.DataRowView' does not contain a property with the name
(4 answers)
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'ProductID'
(3 answers)
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'userid'
(1 answer)
Closed 3 years ago.
I have problems on my dropdown function. The dropdown function suppose to get the values from the database. I think the problem is on the sql select command, but I am new to this kind of stuff (asp.net and sql). can someone help me please, thank you in advance.
this is the SQL DataSourceID
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:*****ConnectionString %>" SelectCommand="SELECT TOP 10
C.CASE_KEY, C.DEPARTMENT_CASE_NUMBER, D.DEPARTMENT_NAME, O.OFFENSE_DESCRIPTION AS CHARGE, LAB_CASE,
OFFENSE_DATE
FROM TV_LABCASE C
INNER JOIN TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE
INNER JOIN TV_OFFENSE O ON C.OFFENSE_CODE = O.OFFENSE_CODE
ORDER BY CASE_DATE DESC
"></asp:SqlDataSource>
Code for the input fields
<table class="style2" >
<tr>
<td class="style3" >Department Case #</td>
<td> <asp:TextBox ID="TextBox1" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Department</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server"
Height="18px" Width="166px" Enabled="False">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Charge</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server"
Height="25px" Width="165px" Enabled="False">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Lab Case #</td>
<td><asp:TextBox ID="TextBox4" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Incident Report Date</td>
<td><asp:TextBox ID="TextBox5" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
</table>
ASP.NET C#(server-side code)
protected void Page_Load(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=A**SE****D***\MSSQL****;Initial Catalog=****;User
ID=****;Password=****";
cnn = new SqlConnection(connetionString);
cnn.Open();
SqlCommand cmd = new SqlCommand("select * from TV_LABCASE", cnn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "DEPARTMENT_NAME";
DropDownList1.DataValueField = "DEPARTMENT_CODE";
DropDownList1.DataBind();
DropDownList2.DataSource = dt;
DropDownList2.DataBind();
DropDownList2.DataTextField = "OFFENSE_DESCRIPTION";
DropDownList2.DataValueField = "OFFENSE_CODE";
DropDownList2.DataBind();
}
Code for the input fields enable the value is true. TRY IT
<table class="style2" >
<tr>
<td class="style3" >Department Case #</td>
<td> <asp:TextBox ID="TextBox1" runat="server" Enabled="true" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Department</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server"
Height="18px" Width="166px" Enabled="true">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Charge</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server"
Height="25px" Width="165px" Enabled="true">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Lab Case #</td>
<td><asp:TextBox ID="TextBox4" runat="server" Enabled="true" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Incident Report Date</td>
<td><asp:TextBox ID="TextBox5" runat="server" Enabled="true" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
</table>
ASP.NET C#(server-side code)
protected void Page_Load(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=A**SE****D***\MSSQL****;Initial Catalog=****;User
ID=****;Password=****";
cnn = new SqlConnection(connetionString);
cnn.Open();
SqlCommand cmd = new SqlCommand(#"SELECT * from TV_LABCASE C Left join TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE Left join TV_OFFENSE O ON C.OFFENSE_CODE = O.OFFENSE_CODE", cnn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "DEPARTMENT_NAME";
DropDownList1.DataValueField = "DEPARTMENT_CODE";
DropDownList1.DataBind();
DropDownList2.DataSource = dt;
DropDownList2.DataBind();
DropDownList2.DataTextField = "OFFENSE_DESCRIPTION";
DropDownList2.DataValueField = "OFFENSE_CODE";
DropDownList2.DataBind();
}
replace your command query to join TV_DEPTNAME table
SqlCommand cmd = new SqlCommand("select C.*, D.DEPARTMENT_NAME from TV_LABCASE C INNER JOIN TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE, ", cnn);
or change your datasource to
DropDownList1.DataSource = SqlDataSource1;
DropDownList1.DataBind();
DropDownList1.DataTextField = "DEPARTMENT_NAME";
DropDownList1.DataValueField = "DEPARTMENT_CODE";
DropDownList1.DataBind();
DropDownList2.DataSource = SqlDataSource1;
DropDownList2.DataBind();
DropDownList2.DataTextField = "CHARGE";
and update your asp:SqlDataSource config
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:*****ConnectionString %>"
SelectCommand="SELECT TOP 10
C.CASE_KEY, C.DEPARTMENT_CASE_NUMBER, D.DEPARTMENT_NAME, O.OFFENSE_DESCRIPTION AS CHARGE, LAB_CASE,
OFFENSE_DATE, C.DEPARTMENT_CODE
FROM TV_LABCASE C
INNER JOIN TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE
INNER JOIN TV_OFFENSE O ON C.OFFENSE_CODE = O.OFFENSE_CODE
ORDER BY C.CASE_DATE DESC"
></asp:SqlDataSource>

Both DataSource and DataSourceID are defined on 'DataList1'. Remove one definition

Heres the dropdownlist and datalist code
<div>
Sort by Category:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>All</asp:ListItem>
<asp:ListItem>Decoration</asp:ListItem>
<asp:ListItem>Catering</asp:ListItem>
<asp:ListItem>Entertainment</asp:ListItem>
<asp:ListItem>Sound</asp:ListItem>
<asp:ListItem>Others</asp:ListItem>
</asp:DropDownList>
<asp:DataList ID="DataList1" runat="server"
GridLines="Both" RepeatColumns="4" RepeatDirection="Horizontal"
Width="1000px" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<table class="nav-justified">
<tr>
<td class="text-center">
<strong>
<asp:Label ID="Label1" runat="server"
Text='<%# Eval("serName") %>'></asp:Label>
</strong>
</td>
</tr>
<tr>
<td>
<asp:Image ID="Image1" runat="server" Height="179px"
ImageUrl='<%# Eval("serImg") %>' Width="191px"/>
</td>
</tr>
<tr>
<td>
<strong>
<asp:Label ID="Label2" runat="server" Text="Rs"></asp:Label>
<asp:Label ID="Label3" runat="server"
Text='<%# Eval("sprice") %>'>
</asp:Label>
</strong>
</td>
</tr>
<tr>
<td class="text-center">
<asp:Button ID="Button1" runat="server" Text="Details" />
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:DataList>
</div>
Here is the .cs code. Its purpose is to filter the data in the list according to the selected category in the dropdown list
protected void Page_Load(object sender, EventArgs e)
{
String conString = ConfigurationManager.ConnectionStrings["regcon"].ConnectionString;
string query = "select * from addService where serCategory=#cat";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#cat", DropDownList1.SelectedItem.Value);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
}
}
}
}
I get the error "Both DataSource and DataSourceID are defined on 'DataList1'. Remove one definition." when i run it.Removing the Datalist1 or DataSourceID would give an error.How do i fix this?
The problem is, on the datalist you have a datasource
DataSourceID="SqlDataSource1"
Then you also apply a data source in the code behind
DataList1.DataSource = ds;
You can't do both. You could remove the existing one in code then apply a new one if you want.

Can't update SQL database

I'm creating a website in ASP.NET (in c#) with campaigns listed into a datalist (seperated from each other by using a <div> in the datalist so each campaign is listed into a block).
I can't update a specific column in the Campaigns table via c# because it can't find the scalar variable #camp_id (the ID of the campaign).
I'm using this command to update:
sqlCmd = "UPDATE Campagnes SET camp_status=2 WHERE camp_id=#camp_id";
Someone who knows how to make it possible to update 'camp_status' to 2 by using the 'camp_id' so only the 'camp_status' of that specific campaign (and not from others in the datalist) will be updated?
Edit: this is my whole code I'm using:
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sqlConn;
string sqlCmd;
sqlConn = #"Data Source=my-ip,1433;Initial Catalog=DbName;
Integrated Security=False;user id=sa;password=password";
sqlCmd= "UPDATE Campagnes SET camp_status=2 WHERE camp_id=#camp_id";
conn.ConnectionString = sqlConn;
cmd.Connection = conn;
cmd.CommandText = sqlCmd;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
So as you can see I'm not using parameters yet because I don't know how to add this and how it reads the value from the database.
The full code I'm using at the moment:
SqlConnection conn2 = new SqlConnection();
SqlCommand cmd2 = new SqlCommand();
string sqlConn2;
string sqlCmd2;
sqlConn2 = #"Data Source=my-ip,1433;Initial Catalog=dbname;Integrated Security=False;user id=sa;password=password";
sqlCmd2 = "select * from Campagnes";
conn2.ConnectionString = sqlConn2;
cmd2.Connection = conn2;
cmd2.CommandText = sqlCmd2;
conn2.Open();
SqlDataReader dr = cmd2.ExecuteReader();
while (dr.Read())
{
id = dr.GetInt32(0);
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sqlConn;
string sqlCmd;
sqlConn = #"Data Source=my-ip,1433;Initial Catalog=dbname;Integrated Security=False;user id=sa;password=password";
sqlCmd = "UPDATE Campagnes SET camp_status=1 WHERE camp_id=" + id;
cmd.Parameters.AddWithValue("#camp_id", id);
conn.ConnectionString = sqlConn;
cmd.Connection = conn;
cmd.CommandText = sqlCmd;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Can't upload my image right here so here an external link to the screenshot: http://i.imgur.com/P8MeKm4.png
As you can see in the image, all the seperated white blocks are one datalist, but seperated by a div that will be generated when a new campaign will be added. When we click the edit button in the bottom of the right, the camp_status needs to be set to 2 (so the admin knows that the campaign needs to be edited).
ASP Source:
div id="popUpPanel">
<p>Waarom vindt u dat deze campagne nog niet in orde is? Geef uw feedback hieronder in:</p>
<asp:TextBox ID="TextBox1" CssClass="box" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="OK" />
</div>
<asp:DataList CellPading="5" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" style="margin-right: 0px" >
<ItemTemplate>
<div class="list" style="padding-left: 25px; padding-right: 10px; padding-top: 10px;">
<asp:Label ID="titelLabel" runat="server" style="font-size: xx-large" Text='<%# Eval("titel") %>' />
<br />
<asp:Label ID="Label1" runat="server" style="font-size: xx-large; display: none;" Text='<%# Eval("camp_id") %>' />
<asp:Label ID="datum_geplaatstLabel" runat="server" Text='<%# Eval("datum_geplaatst") %>' />
<br /><br />
<strong>Korte beschrijving:</strong><br />
<asp:Label ID="korte_beschrijvingLabel" runat="server" Text='<%# Eval("korte_beschrijving") %>' />
<br /><br />
<strong>Lange beschrijving:</strong><br />
<asp:Label ID="lange_beschrijvingLabel" runat="server" Text='<%# Eval("lange_beschrijving") %>' />
<br />
<table class="auto-style1">
<tr>
<td class="auto-style2"><strong>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/edit.png" OnClientClick="showPopUp(); return false;" Style="margin-left:9px;" />
</strong></td>
<td><strong>
<asp:ImageButton ID="ImageButton1" runat="server" asp:Imagebutt="" ImageUrl="~/img/vink.png" Style="margin-left:0px;" />
</strong></td>
</tr>
</table>
<br />
</div>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebhoostConnectionString %>" SelectCommand="SELECT [titel], [datum_geplaatst], [korte_beschrijving], [lange_beschrijving], [camp_id] FROM [Campagnes]"></asp:SqlDataSource>
So when we click on the 'Button1' in the PopupPanel the camp_status needs to be set to 2 only of that specific campaign. As you can see in the source I was also trying to use the label I was talking about, but everytime a new div is created, all coming labels will have 'Label1' as ID so it will also pick all campaign ID's and not just one..
ASP source code (using the CommandArgument in the button):
<div id="popUpPanel">
<p>Waarom vindt u dat deze campagne nog niet in orde is? Geef uw feedback hieronder in:</p>
<asp:TextBox ID="TextBox1" CssClass="box" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" CommandArgument='<%= Campagnes.camp_id %>' />
</div>
<asp:DataList CellPading="5" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" style="margin-right: 0px" >
<ItemTemplate>
<div class="list" style="padding-left: 25px; padding-right: 10px; padding-top: 10px;">
<asp:Label ID="titelLabel" runat="server" style="font-size: xx-large" Text='<%# Eval("titel") %>' />
<br />
<asp:Label ID="Label1" runat="server" style="font-size: xx-large; display: none;" Text='<%# Eval("camp_id") %>' />
<asp:Label ID="datum_geplaatstLabel" runat="server" Text='<%# Eval("datum_geplaatst") %>' />
<br /><br />
<strong>Korte beschrijving:</strong><br />
<asp:Label ID="korte_beschrijvingLabel" runat="server" Text='<%# Eval("korte_beschrijving") %>' />
<br /><br />
<strong>Lange beschrijving:</strong><br />
<asp:Label ID="lange_beschrijvingLabel" runat="server" Text='<%# Eval("lange_beschrijving") %>' />
<br />
<table class="auto-style1">
<tr>
<td class="auto-style2"><strong>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/edit.png" OnClientClick="showPopUp(); return false;" Style="margin-left:9px;" />
</strong></td>
<td><strong>
<asp:ImageButton ID="ImageButton1" runat="server" asp:Imagebutt="" ImageUrl="~/img/vink.png" Style="margin-left:0px;" />
</strong></td>
</tr>
</table>
<br />
</div>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebhoostConnectionString %>" SelectCommand="SELECT [titel], [datum_geplaatst], [korte_beschrijving], [lange_beschrijving], [camp_id] FROM [Campagnes]"></asp:SqlDataSource>
C# source code (edited EventArgs to CommandEventArgs e):
string id;
SqlConnection conn2 = new SqlConnection();
SqlCommand cmd2 = new SqlCommand();
string sqlConn2;
string sqlCmd2;
sqlConn2 = #"Data Source=81.169.242.73,1433;Initial Catalog=Webhoost;Integrated Security=False;user id=sa;password=63310Kw1c";
sqlCmd2 = "select * from Campagnes";
conn2.ConnectionString = sqlConn2;
cmd2.Connection = conn2;
cmd2.CommandText = sqlCmd2;
conn2.Open();
SqlDataReader dr = cmd2.ExecuteReader();
while (dr.Read())
{
id = e.CommandArgument.ToString();
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sqlConn;
string sqlCmd;
sqlConn = #"Data Source=81.169.242.73,1433;Initial Catalog=Webhoost;Integrated Security=False;user id=sa;password=63310Kw1c";
sqlCmd = "UPDATE Campagnes SET camp_status=1 WHERE camp_id=" + id;
cmd.Parameters.AddWithValue("#camp_id", id);
conn.ConnectionString = sqlConn;
cmd.Connection = conn;
cmd.CommandText = sqlCmd;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
You have to define and add the parameter #camp_id
cmd.Parameters.AddWithValue("#camp_id", youCampIdValue);

How to use the DropDownList's SelectedIndexChanged event

I have two DropDownLists in my webform and when I select a value in the first dropdownlist, I would like a related value to be automatically selected in the second dropdownlist.
This is what I currently have:
<table>
<tr>
<td>
<asp:Label ID="lbmanu" runat="server" Text="Furniture Manufacturer :
"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddmanu" runat="server"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="Sql_fur_model_manu" runat="server"
ConnectionString="<%$ ConnectionStrings:conStr %>"
SelectCommand="SELECT DISTINCT [manufacturer] FROM
[furniture_manufacturer]">
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lbtype" runat="server" Text="Furniture Type :
"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddtype" runat="server" AutoPostBack="True">
</asp:DropDownList>
</td>
</tr>
</table>
Code Behind :
protected void ddmanu_SelectedIndexChanged(object sender, EventArgs e)
{
string query = "select furniture from furniture_model where manufacturer='" +
ddmanu.SelectedValue.ToString() + "'";
con.Open();
cmd = new SqlCommand(query, con);
DataTable dt = Select(query);
cmd.ExecuteNonQuery();
ddtype.DataSource = dt;
ddtype.DataTextField = "manufacturer";
ddtype.DataValueField = "furniture";
ddtype.DataBind();
}
You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
AutoPostBack="True" AppendDataBoundItems="true">
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList2
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList3
}
I think this is the culprit:
cmd = new SqlCommand(query, con);
DataTable dt = Select(query);
cmd.ExecuteNonQuery();
ddtype.DataSource = dt;
I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":
cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();
Or you can create a DataTable as explained here:
cmd = new SqlCommand(query, con);
SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);
ddtype.DataSource = listTable;

GridView doesn't show

Working on a basic C# web app here and I can't seem to get the GridView to show. I can see that its passing the code through because it changes my image from one to another but for some reason the Gridview doesn't show up. Using the button for the postback and my dropdown box has the variable for my stored procedure. I'm new to C# web apps (Vb Win app guy here) so I need a little guidance please.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
//This is where my postback begins...
if (IsPostBack)
{
string Quote = null;
System.Data.SqlClient.SqlConnection myDatabaseConnection = null;
System.Data.SqlClient.SqlCommand myCommand = null;
System.Data.SqlClient.SqlDataReader myReader = null;
// Validate the SP
Page.Validate();
if (Page.IsValid)
{
Quote = DropDownList1.Text.ToString();
try
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Data1"].ConnectionString;
myDatabaseConnection = new System.Data.SqlClient.SqlConnection(connectionString);
myCommand = new System.Data.SqlClient.SqlCommand();
//Set up to use my stored procedure:
myCommand.CommandType = System.Data.CommandType.StoredProcedure;
myCommand.Connection = myDatabaseConnection;
myCommand.CommandText = "EditDataPage";
myCommand.Parameters.AddWithValue("#QuoteNumber", Quote);
//Use an SqlDataReader to execute the stored procedure and
//get the results into the GridView:
myDatabaseConnection.Open();
myReader = myCommand.ExecuteReader();
GridView1.DataSource = myReader;
GridView1.DataBind();
myDatabaseConnection.Close();
myDatabaseConnection.Dispose();
GridView1.Visible = true;
Image1.Visible = false;
Image2.Visible = true;
}
catch (System.Data.SqlClient.SqlException exception)
{
ErrorLabel.Visible = true;
}
catch (Exception exception)
{
ErrorLabel.Visible = true;
//Do cleanup tasks here:
}
finally
{
myCommand = null;
if ((myReader != null) && !myReader.IsClosed)
{
myReader.Close();
}
myReader = null;
if ((myDatabaseConnection != null) && myDatabaseConnection.State == System.Data.ConnectionState.Open)
{
myDatabaseConnection.Close();
myDatabaseConnection.Dispose();
}
myDatabaseConnection = null;
}
}
}
}
}
Heres my aspx code:
Edit Data
Use the controls to move within the dataset, then edit and save what you need
for your reports.
<table class="yui-d0f">
</table>
<table class="yui-main">
<tr>
<td>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Data1 %>"
SelectCommand="EditDataPage" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:FormParameter FormField="DropDownList1" Name="QuoteNumber" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<table class="style1">
<tr>
<td align="center">
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="DropDownList"
DataTextField="QuoteNumber" DataValueField="QuoteNumber" Height="23px"
Width="188px">
</asp:DropDownList>
<asp:SqlDataSource ID="DropDownList" runat="server"
ConnectionString="<%$ ConnectionStrings:Data1 %>"
SelectCommand="SELECT QuoteNumber FROM SF1411 GROUP BY QuoteNumber">
</asp:SqlDataSource>
</td>
<td>
<table class="style1">
<tr>
<td class="style2">
<asp:Button ID="ListAllButton" runat="server" Height="32px" Text="Show Data"
Width="111px" PostBackUrl="~/EditData.aspx" />
</td>
<td>
<asp:Image ID="Image1" runat="server"
ImageUrl="~/_assets/img/lock-disabled-icon.png" />
<asp:Image ID="Image2" runat="server" ImageUrl="~/_assets/img/lock-icon.png"
Visible="False" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<asp:Label ID="ErrorLabel" runat="server" Font-Underline="True"
ForeColor="Maroon" Text="Error in Processing, try again later." Visible="False"></asp:Label>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
AutoGenerateColumns="False">
</asp:GridView>
I'm not 100% sure, but the fact that you've got AutoGenerateColumns="false" on your GridView yet no columns defined looks a bit suspicious. I guess as a quick test you could change this attribute to true and see what happens.
If you do indeed want to specify the columns yourself (which in my experience is the norm), then you need to specify them, like this for example:
<asp:GridView ...>
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField>
<asp:Label Text='<%# Eval("Surname") %>' runat="server" />
</asp:TemplateField>
</Columns>
</asp:GridView>
See MSDN for more details.

Categories