Tying to print out a datatable in C#. Used a directive of "using System.Data;". No errors occurring in the program but it does not print out the datatable. LgeoEPH[k] anf BgeoEPH[k]
exist.
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.IO;
using System.Text;
in a subroutine:
DataTable dtz = new DataTable();
dtz.Columns.Add("", typeof(string));
dtz.Columns.Add("Sun", typeof(double));
dtz.Columns.Add("Moon", typeof(double));
dtz.Rows.Add("LgeoEPH", LgeoEPH[0], LgeoEPH[1], LgeoEPH[2], LgeoEPH[3], LgeoEPH[4], LgeoEPH[5], LgeoEPH[6], LgeoEPH[7], LgeoEPH[8], LgeoEPH[9], LgeoEPH[10]);
dtz.Rows.Add("BgeoEPH", BgeoEPH[0], BgeoEPH[1], BgeoEPH[2], BgeoEPH[3], BgeoEPH[4], BgeoEPH[5], BgeoEPH[6], BgeoEPH[7], BgeoEPH[8], BgeoEPH[9], BgeoEPH[10]);
DataView dvz = new DataView(dtz);
Based on the following using directives:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
it seems that you may be attempting to display a DataTable on a WebForm.
Prerequisite
If developing on Win 10, ensure that IIS is enabled/installed (Control Panel => View by: Small icons => Programs and Features => Turn Windows features on or off => check "Internet Information Services" => expand "Internet Information Services" => expand "World Wide Web Services" => expand "Application Development Features" => check "ASP.NET 4.8" => click "OK")
Try the following:
VS 2022:
Create a new ASP.NET Web Application (.NET Framework)
Open Visual Studio 2022
Click Create a new project
For filter, select
Select ASP.NET Web Application (.NET Framework)
Click Next
Enter desired project name (ex: WebAppGridViewTest)
Select desired framework (ex: .NET Framework 4.8)
Click Create
On the "Create a new ASP.NET Web Application" form, select Empty.
If you're using "http" instead of "https", under "Advance", uncheck "Configure for HTTPS".
Click Create
Add Web Form to project
In VS menu, click Project
Select Add New Item...
On left side, expand "Web". Select Web Form (name: default.aspx)
Click Add
Open Solution Explorer
In VS menu, click View
Select Solution Explorer
default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebAppGridViewTest._default" %>
<!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 ID="LabelMsg" runat="server" Text="" style="position:absolute;left:50px; top:60px"></asp:Label>
</div>
<div style="position:absolute;left:50px; top:100px">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" GridLines="Both">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-HorizontalAlign="Center" Visible="True" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" ItemStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
In Solution Explorer, expand "default.aspx" and select "default.aspx.cs".
default.aspx.cs
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebAppGridViewTest
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("FirstName", typeof(string)));
dt.Columns.Add(new DataColumn("LastName", typeof(string)));
//add test data
AddRow(dt, 1, "John", "Doe");
AddRow(dt, 2, "Tom", "Smith");
AddRow(dt, 3, "Susan", "Archer");
GridView1.DataSource= dt;
GridView1.DataBind();
}
private void AddRow(DataTable dt, int id, string firstName, string lastName)
{
DataRow row = dt.NewRow();
row["ID"] = id;
row["FirstName"] = firstName;
row["LastName"] = lastName;
//add
dt.Rows.Add(row);
}
}
}
Result:
Resources
Display varbinary Image in Gridview
Related
I'm trying to create a site that allows the user to upload a song and download any song that was uploaded. I'm using MySQL to store any uploaded song. I think I have the HTML and C# code right but it keeps throwing me an error saying FileUpload1 does not exist in the current context, you can use a navigation bar to switch context. My C# code is as follows.
using System;
using System.Collections.Generic;
using System.Web;
using System.Xml.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.IO;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Configuration;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
string strConnString = "server=localhost;user id=root;database=music;persistsecurityinfo=True";
using (MySqlConnection con = new MySqlConnection(strConnString))
{
using (MySqlCommand command = new MySqlCommand())
{
con.Open();
string SQL = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
command.CommandText = SQL;
command.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
command.Parameters.AddWithValue("#ContentType", "audio/mpeg3");
command.Parameters.AddWithValue("#Data", bytes);
command.Connection = con;
command.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
Here is my HTML for the site:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Music.aspx.cs" Inherits="Default3" %>
<asp:Content ID="music" runat="server" ContentPlaceHolderID ="ContentPlaceHolder1">
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click"/>
<hr/>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" RowStyle-BackColor="#A1DCF2" Font-Names = "Arial" Font-Size = "10pt"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
<Columns>
<asp:BoundField DataField="Name" HeaderText="FileName"/>
<asp:TemplateField>
<ItemTemplate>
<object type="application/x-shockwave-flash" data='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'
width="240" height="20" id="dewplayer">
<param name="wmode" value="transparent"/>
<param name="movie" value='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'/>
</object>
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="Id" Text = "Download" DataNavigateUrlFormatString = "~/File.ashx?Id={0}" HeaderText="Download"/>
</Columns>
</asp:GridView>
</asp:Content>
Your code behind defines a partial class "Default3". I assume your aspx page is named "Default3", and visual studio has generated the code to instantiate the elements in that aspx page. That generated code is also a partial class "Default3", but you will notice in that generated code, that the partial class is defined under a namespace. Your code behind does not define the rest of that class under any namespace, so it does not have access to the same objects. Looks like at some point you deleted the namespace specification out of your code behind.
I am trying to implement a search textbox with the Ajax Control Toolkit AutoCompleteExtender. The result should be a list of names matching the entered text however what gets displayed is the page source HTML, character by character, creating an extremely long list of single letters.
I have found and tried several samples but cannot get this to work. I am certain the database connection is valid and the SQL query when executed directly in MSSMS, returns the expected result. The AjaxControlToolkit is installed and works on other pages in the solution.
This issue was asked before ("Ajax Control Toolkit AutoCompleteExtender displays html source character by character of the current page as autocomplete suggestion list"). However for reasons of simplicity and maintainability I do not want to implement a WebService as this poster did.
acex.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoCompleteExtender - Last Names</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:TextBox ID="txbxLastName" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txbxLastName"
MinimumPrefixLength="2"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="1000"
ServiceMethod="GetLastNames">
</asp:AutoCompleteExtender>
</div>
</form>
</body>
</html>
acex.aspx.cs
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MCA
{
public partial class acex : System.Web.UI.Page
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetLastNames(string prefixText)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand cmd = new SqlCommand("SELECT [Last_Name] FROM [Entity_Person] WHERE [Last_Name] LIKE #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
List<string> LastNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
LastNames.Add(dt.Rows[i][0].ToString());
}
return LastNames;
}
}
}
i want to show a value in DropDownList at page load and the value is "1 Year".
here is my Database Table
id instal
0 Choose
6 6 Month
12 1 Year
24 2 Year
36 3 Year
here is my ASPX code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="instal" DataValueField="id"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:paconn %>"
SelectCommand="SELECT * FROM [cms_instal] ORDER BY [id]">
</asp:SqlDataSource>
</asp:Content>
and its my C# code:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Collections;
using System.Web.SessionState;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.Text = "1 Year";
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
but problem is that when my page is loaded it gives an error
"'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value"
i am using ASP.Net C#, SQL Server 2008.
The text property of a DropDownList gets or sets the SelectedValue. Since your DataValueField is set to "id", you would need to set the Text property to "12".
Move the text to the LoadComplete event
void Page_LoadComplete(object sender, EventArgs e)
{
DropDownList1.Text = "1 Year";
}
The list binding has not occurred in page load so the list is not able to take another value which is not in the list. Setting the value after page load will allow it to use an existing value.
what i have done is login and the username appears in my masterpage in a label. what i need to do is if the logged in user has admin permission make visible controls on several child pages (including a gridview deletecontrol that is there on one child page). have be struggling to figure it out. just want to learn.
Is there a way to class all the controls under a class call admin and call from masterpage on checking user permission?
Loginpage code behind
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.Adapters;
public partial class login1 : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
}
protected void LoginButton_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = WCGSQL.showdata("select * from Login where Username='" + UserName.Text + "' and Password='" + Password.Text + "'");
if (ds.Tables[0].Rows.Count != 0)
{
Session["Username"] = UserName.Text;
Response.Redirect("Home.aspx");
}
else
{
FailureText.Visible = true;
FailureText.Text = "Invalid Login";
}
}
}
App/code code behind
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public class WCGSQL
{
static SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|WCG.mdf;Integrated Security=True;User Instance=True");
static public Boolean savedata(string qurt)
{
try
{
SqlCommand cmd = new SqlCommand(qurt, con);
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
con.Close();
}
}
static public DataSet showdata(string qurt)
{
DataSet ds = new DataSet();
try
{
SqlDataAdapter adp = new SqlDataAdapter(qurt, con);
adp.Fill(ds);
return ds;
}
catch
{
return ds;
}
}
}
You want to use the LoginView control. See ASP.NET Login Controls Overview to learn about the entire suite.
Example from MSDN:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<p>
<asp:LoginStatus id="LoginStatus1" runat="server"></asp:LoginStatus></p>
<p>
<asp:LoginView id="LoginView1" runat="server">
<AnonymousTemplate>
Please log in for personalized information.
</AnonymousTemplate>
<LoggedInTemplate>
Thanks for logging in
<asp:LoginName id="LoginName1" runat="Server"></asp:LoginName>.
</LoggedInTemplate>
<RoleGroups>
<asp:RoleGroup Roles="Admin">
<ContentTemplate>
<asp:LoginName id="LoginName2" runat="Server"></asp:LoginName>, you
are logged in as an administrator.
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView></p>
</form>
</body>
</html>
if (HttpContext.Current.User.IsInRole("member"))
{
//enable/disable here
}
Hey i'd done one application like this. What you need to do is make separate web-pages (i.e. after login pages) for both admin and other users. Then you can easily authenticate admin through his credentials and redirected to the respective page. There you can placed some controls according to the need.
And if your concern is to create an application like control-access board where admin can give permissions to modules to what to show on child pages of other users then let me know through your reply.
currently I have a web which loads excel spreadsheet data into SQL database. When the page loads, all the parameters are hard coded on the code behind, so I do not have 'browse for file' and 'upload' button. I would like to implement these 2 buttons but I am not sure how should I do it.
I am using C# language, Visual Studio 2005 and SQL Server 2005.
Below is the code which runs the import of excel data into the database:
importexcel.aspx.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
public partial class ImportExcel : System.Web.UI.Page
{
public static string path = #"c:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\insqlserver\studentsheet1.xls";
public static string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
protected void Page_Load(object sender, EventArgs e)
{
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(connStr))
{
OleDbCommand command = new OleDbCommand
("Select StudentName,RollNo,Course FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<database>;User ID=<userid>;Password=<password>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "tStudent";
bulkCopy.WriteToServer(dr);
}
}
}
}
}
Below is my code for the my current html:
importexcel.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ImportExcel.aspx.cs" Inherits="ImportExcel" %>
<!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></title>
<script language="javascript" type="text/javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
Please select a Excel spreadsheet to import:<br />
<asp:FileUpload ID="fupExcel" runat="server" />
<br />
<br />
<asp:Button ID="btnImport" runat="server"
Text="Import" onclick="btnImport_Click" />
<br />
<br />
<a href=http://localhost:1701/SoD>Click to go to main page</a>
</form>
</body>
</html>
I am not sure how do I attach the 2 buttons to my background code, someone teach me? Best if with sample code, thanks a lot!
First, the code in your page load needs to execute only if(IsPostBack) or on button click.
Second, (At leas modern) browsers won't let you change the value of the input file field, or click it.
You might try with some flash upload thing or so, but I don't expect much.