I am trying to display data in Gridview in c#. I have been asked to make the gridview look as close as a table in SQL database. I have been able to achieve a bit but my grid is far from a Sql table. Can someone help me out? This is what I tried so far.
Aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Reports.aspx.cs" Inherits="Reports" %>
<!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="Label1" runat="server" Text="Enter Query"></asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<div id="grdCharges" runat="server" style="width: 875px; overflow: auto; height: 600px;">
<asp:GridView ID="grd1" runat="server" AutoGenerateColumns="true" Width="150%">
</asp:GridView>
</div>
</p>
</form>
</body>
</html>
C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Reports : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = null;
SqlDataReader reader = null;
try
{
string q = TextBox1.Text.ToString();
string strcon = "Data Source=***********";
con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = q;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
var dataTable = new DataTable();
dataTable.Load(reader);
grd1.DataSource = dataTable;
grd1.DataBind();
}
catch (Exception ex)
{
//....
}
finally
{
if(reader != null)
reader.Close();
if(con != null && con.ConnectionState != ConnectionState.Closed)
con.Close();
}
}
}
This is how my table looks like -
Current table -
Current table
Target table -
Targettable
Related
I have created the table cm_table and cm_table_copy on MySQL database.
On cm_table I have recorded three rows, instead the cm_table_copy is empty
After that added new web form to website.
Drag and drop a Repeater control from Toolbox>Data to .aspx page.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Repeater.aspx.cs" Inherits="Repeater" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="repcomment" runat="server">
<ItemTemplate>
<fieldset>
<legend style="font-size: 12px; font-weight: bold; color: Red; margin-left: 10px;">
Repeater control in Asp.net
</legend>
<div class="pure-g">
<div class="pure-u-1 pure-u-md-1-3">
Comment
<asp:TextBox ID="txComment" runat="server" Text='<%#Eval("Comment").ToString()%>'>
</asp:TextBox>
</div>
</div>
<br />
<div class="container">
<asp:ImageButton ID="btn" runat="server" ValidationGroup="Validation2"
OnClick="btn_Click"
ImageUrl="/Images/edit_button.gif"
OnClientClick="if (!confirm('Confirm?')) return false;"
CausesValidation="true" />
</div>
</fieldset>
<br />
</ItemTemplate>
</asp:Repeater>
</div>
<asp:ValidationSummary ID="ValidationSummary1"
ValidationGroup="Validation2" runat="server"
ShowSummary="false"
ShowMessageBox="true"
CssClass="validation-summary-errors" />
</form>
</body>
</html>
I should see on the web browser the three rows recorded on cm_table and when the comment on cm_table is edited I need register the new comment on cm_table_copy
But I have this error on first access to aspx page
CS0103: The name 'txComment' does not exist in the current context
How to do resolve this?
My code-behind below
Can you help me, please?
Thank you in advance for any help
using System;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Web.UI;
public partial class Repeater : Page
{
protected void btn_Click(object sender, ImageClickEventArgs e)
{
string sql = String.Format(" INSERT INTO cm_table_copy (Comment, LatestComment) ");
sql += String.Format(" VALUES(?, CURRENT_TIMESTAMP()); ");
using (OdbcConnection myConnectionString =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ca"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, myConnectionString))
{
try
{
command.Parameters.AddWithValue("param1", txComment.Text.Replace("'", "`").ToString().ToUpper()); //<<<Line of error
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sql = #String.Format(" SELECT * FROM cm_table; ");
using (OdbcConnection myConnectionString =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ca"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, myConnectionString))
{
try
{
command.Connection.Open();
DataSet ds = new DataSet();
OdbcDataAdapter adp = new OdbcDataAdapter(command);
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
repcomment.DataSource = ds;
repcomment.DataBind();
}
}
catch (Exception ex)
{
throw new ApplicationException("operation failed!", ex);
}
finally
{
command.Connection.Close();
}
}
}
}
}
}
Update #01
I have tried this but the FindControl always returns null
protected void btn_Click(object sender, ImageClickEventArgs e)
{
TextBox txComment = (TextBox)repcomment.FindControl("txComment");
}
I'm trying to insert simple data in mysql database on a button click but whenever I try to do so, the button click is processed but the data is not getting inserted and also there are no exceptions or errors. I have the database stored in my localhost with exact same table name and column name yet it is creating the problem. Don't know the issue seems to be.
testing.aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="testing.aspx.cs" Inherits="CricketAnalysis2.testing" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<p>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</p>
</form>
</body>
</html>
testing.aspx.cs file
using System;
using MySql.Data.MySqlClient;
using System.Data;
namespace CricketAnalysis2
{
public partial class testing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(#"Data Source=localhost;port=3306;Initial Catalog=cricdb;User Id=root;password=''");
con.Open();
MySqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "INSERT INTO drug VALUES ('"+TextBox1.Text+"')";
con.Close();
}
}
}
The issue is you're not executing the command. You need to call ExecuteNonQuery() method so:
cmd1.ExecuteNonQuery();
Furthermore, your query is currently open to sql injection, to avoid that you should use paramertised queries and also make use of using block to ensure the object is disposed correctly.
var connectionString = "Data Source=localhost;port=3306;Initial Catalog=cricdb;User Id=root;password=''\"";
var query = "INSERT INTO DRUG VALUES(#ParameterName)";
using (var con = new MySqlConnection(connectionString))
{
using (var cmd = new MySqlCommand(query, con))
{
cmd.Parameters.Add("#ParameterName", MySqlDbType.VarChar).Value = TextBox1.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
i have write a code to fetch the video from the server folder and play it on web page. i am using flowplayer.it shows the video player with controls but not playing the video.what could be the problem . code is attached
Code in aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebsiteTaskAsp.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="FlowPlayer/flowplayer-3.2.12.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 73px">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Label ID="lblFilename" runat="server" Text="File Name :"></asp:Label>
<asp:Label ID="lblUploadMsg" runat="server"></asp:Label>
<asp:TextBox ID="videoNameTextbox" runat="server"></asp:TextBox>
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" /><br /><br />
</div>
<div>
<hr />
<asp:DataList ID="DataList1" Visible="true" runat="server" AutoGenerateColumns="false"
RepeatColumns="2" CellSpacing="5">
<ItemTemplate>
<u>
<%# Eval("vname") %></u>
<hr />
<a class="player" style="height: 300px; width: 300px; display: block" href='<%# Eval("vpath") %>'>
</a>
</ItemTemplate>
</asp:DataList>
<script src="FlowPlayer/flowplayer-3.2.12.min.js" type="text/javascript"></script>
<script type="text/javascript">
flowplayer("a.player", "FlowPlayer/flowplayer-3.2.16.swf", {
plugins: {
pseudo: { url: "FlowPlayer/flowplayer.pseudostreaming-3.2.12.swf" }
},
clip: { provider: 'pseudo', autoPlay: false },
});
</script>
</div>
</form>
</body>
</html>
**Code in aspx.cs**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace WebsiteTaskAsp
{
public partial class index : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=Khawaja\\SQLEXPRESS;Initial Catalog=TaskDB;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
using (SqlConnection con = new SqlConnection("Data Source=Khawaja\\SQLEXPRESS;Initial Catalog=TaskDB;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select * from videos";
cmd.Connection = con;
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if(FileUpload1.HasFile)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//UploadedVideos//"+str);
string path = "~//UploadedVideos//"+str.ToString();
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO videos VALUES('"+videoNameTextbox.Text+"','"+path+"')",con);
cmd.ExecuteNonQuery();
con.Close();
lblUploadMsg.Text = "Video Uploaded Successfully";
}
}
}
}
Getting an error that has crashed my entire site. The wait operation is timing out, i have read the documentation on using{} blocks but cannot understand why this is happening. Any help is appreciated.
[Win32Exception (0x80004005): The wait operation timed out]
The page i have been working on most recently is
itemediting.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="itemediting.aspx.cs" Inherits="admin_itemediting" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>elmtree - Admin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" />
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../styles/mylist.css" />
</head>
<body>
<form id="form1" runat="server">
<img src="images/ELleft.png" style="width:226px; height:52px; margin-top: 3px; margin-left: 17px; text-align: justify; float: none;"/></a></li>
<div class="container">
<h1> Item Edit </h1> </div>
<div class="container">
<div class="form-group">
<label class="col-sm-2 control-label">Item name: </label>
<div class="col-md-4">
<asp:TextBox ID="itemnametext" runat="server" Text="" CssClass="form-control">
</asp:TextBox>
</div>
<div class="pull-right">
<asp:Button CssClass="btn btn-primary btn-lg" ID="updatebutton" role="button" runat="server" Text="save" OnClick="updatebutton_Click" />
</div>
</div>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class admin_itemediting : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int row = 0;
if (Request.QueryString["itemID"] != null)
{
row = int.Parse(Request.QueryString["itemID"]);
}
else
{
Response.Redirect("itemedit.aspx");
}
}
string connectionString = WebConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
string query = "SELECT * FROM reports WHERE ID=#rowid";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#rowid", row);
SqlDataReader rdr = myCommand.ExecuteReader();
while (rdr.Read())
{
string myname = rdr["itemname"].ToString();
itemnametext.Text = myname;
}
}
protected void updatebutton_Click(object sender, EventArgs e){
string connectionString = WebConfigurationManager.ConnectionStrings ["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
string itemnametextupdate = itemnametext.Text;
string query = "UPDATE reports SET itemname = #itemnewname";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#itemnewname", itemnametextupdate);
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("updateimage.aspx");
}
public object row { get; set; }
}
Just a suggestion.
if (!IsPostBack)
{
int row = 0;
if (Request.QueryString["itemID"] != null)
{
row = int.Parse(Request.QueryString["itemID"]);
}
else
{
// here even if you make redirect the code continue to run
// and you do not know whats going on then... a call to db and a redirect.
Response.Redirect("itemedit.aspx");
// so here add a return;
return;
}
}
Next possible bug is that on post back the row is not saved on viewstate and take a default value. Make your row variable as:
int cRow
{
set
{
ViewState["cRow"] = value;
}
get
{
if (ViewState["cRow"] != null)
return Convert.ToInt32(ViewState["cRow"]);
else
return -1;
}
}
i want to add comments from my database to the update panel on click of a button.
this is my aspx page-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default12.aspx.cs" Inherits="Default12" %>
<!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:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Button ID="Button" runat="server" Text="Button" onclick="Button_Click" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button" EventName = "Click"/>
</Triggers>
<ContentTemplate>
<asp:PlaceHolder ID="CommentPlaceHolder" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
this is my cs page-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.SqlClient;
using System.Data;
public partial class Default12 : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
string str;
protected void Page_Load(object sender, EventArgs e)
{
str = #"Data source=INSPIRATION\SQLEXPRESS; Initial Catalog=ComputerPedia; Integrated security= true";
con = new SqlConnection(str);
if (con.State == ConnectionState.Closed)
con.Open();
cmd = new SqlCommand("Select Comment from CommentTable", con);
dr = cmd.ExecuteReader();
}
protected void Button_Click(object sender, EventArgs e)
{
dr.Read();
Response.Write(dr[0].ToString());
Label l = new Label();
l.ID = "l1";
l.Text = dr[0].ToString();
CommentPlaceHolder.Controls.Add(l);
UpdatePanel1.Update();
}
}
but this is not working. There is no problem with the connection because ic opied the connection code from a working webpage and the query is also working in sql. please help me with this. Thanks!
Please use the modified code to complete your operation. I have commented the modified section and have written suitable explantion for it.
<!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:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button"/> //modified
</Triggers>
<ContentTemplate>
<asp:Button ID="Button" runat="server" Text="Button" onclick="Button_Click" /> // modified
<asp:PlaceHolder ID="CommentPlaceHolder" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
This was your aspx code
Here comes your .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.SqlClient;
using System.Data;
using System.Data.SqlClient;
using System.Data;
public partial class Default12 : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
string str;
protected void Page_Load(object sender, EventArgs e)
{
str = #"Data source=INSPIRATION\SQLEXPRESS; Initial Catalog=ComputerPedia; Integrated security= true";
con = new SqlConnection(str);
if (con.State == ConnectionState.Closed)
con.Open();
cmd = new SqlCommand("Select Comment from CommentTable", con);
dr = cmd.ExecuteReader();
}
protected void Button_Click(object sender, EventArgs e)
{
if (reader.HasRows) // to check whether there are comments or not in your database
{
int commentIndexForLabel = 1;
while (reader.Read())
{
// Response.Write(dr[0].ToString());
Label l = new Label();
l.ID = "l" + commentIndexForLabel.ToString() ; //modified
l.Text = (string)dr["Comment"]; //modified
CommentPlaceHolder.Controls.Add(l);
commentIndexForLabel ++;
//UpdatePanel1.Update(); This is not required
}
}
else
{
// do whatever you want to do if there are no comments
}
}
}
Use this code and share your output here. I hope things will work well