I have written a user control an editable GridView. Here is the code of the control in design (file: editableGridView.ascx)
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="editableGridView.ascx.cs" Inherits="WebApplication1.EditableGridView" %>
<asp:GridView ID="EditableGrid" runat="server" Width="500px" Height="500px" AllowSorting="True"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
OnRowEditing="EditableGrid_RowEditing"
OnRowCancelingEdit="EditableGrid_RowCancelingEdit"
OnRowUpdating="EditableGrid_RowUpdating"
OnRowDeleting="EditableGrid_RowDeleting"
></asp:GridView>
And here is the code behind: (File: editableGridView.ascx.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;
using System.Data.Sql;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class EditableGridView : System.Web.UI.UserControl
{
public string connstr { get; set; }
public string tablename { get; set; }
public string selectcmd { get; set; }
private List<EdField> fields;
private SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
}
public void InitGrid(string theconnstr, string tablename)
{
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (!rd.HasRows) return;
fields = new List<EdField>();
for (int i =0; i < rd.FieldCount; i++)
{
fields.Add(new EdField(rd.GetName(i), rd.GetDataTypeName(i)));
}
}
}
}
public void Bind()
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = selectcmd;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
EditableGrid.DataSource = dt;
EditableGrid.DataBind();
EditableGrid.Visible = true;
}
}
}
con.Close();
}
protected void EditableGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
EditableGrid.EditIndex = e.NewEditIndex;
Bind();
}
protected void EditableGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EditableGrid.EditIndex = -1;
Bind();
}
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)EditableGrid.Rows[e.RowIndex];
List<TextBox> tbs = new List<TextBox>();
for (int i = 1; i < fields.Count; i++)
{
tbs.Add((TextBox)row.FindControl("textbox" + i.ToString()));
}
EditableGrid.EditIndex = -1;
String sql = "UPDATE " + tablename + "SET " ;
for (int i = 1; i < fields.Count; i++)
{
sql += fields[i].Name;
sql += " = ";
sql += ProperFormatField(fields[i].DataTypeName, tbs[i].Text);
if (i < fields.Count - 1)
{
sql += " , ";
}
}
Label lbl = (Label)row.FindControl("lblid");
sql += " WHERE " + fields[0].Name + " = " + lbl.Text;
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
Bind();
}
protected void EditableGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)EditableGrid.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
String sql = "DELETE " + tablename;
sql += " WHERE " + fields[0].Name + " = " + lbl.Text;
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
Bind();
/* */
}
private String ProperFormatField(String dtf, String s)
{
if (
(dtf == "CHAR") ||
(dtf == "VARCHAR") ||
(dtf == "NVARCHAR") ||
(dtf == "NCHAR") ||
(dtf == "DATE") ||
(dtf == "DATETIME") ||
(dtf == "DATETIME2")
)
{
return "'" + s + "'";
}
else
return s;
}
}
public class EdField
{
private String myName;
private String myDataTypeName;
public String Name
{
get { return myName; }
set { myName = value; }
}
public String DataTypeName
{
get { return myDataTypeName; }
set { myDataTypeName = value; }
}
public EdField(String theName, String theDataTypename)
{
myName = theName;
myDataTypeName = theDataTypename.ToUpper();
}
}
}
Now in my page where I want to place my control I write:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>
<%# Register TagPrefix="mygrids" TagName="EditableGridView" Src="editableGridView.ascx"%>
<!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>
<mygrids:EditableGridView ID="edgv1"></mygrids:EditableGridView>
</div>
</form>
</body>
</html>
But there is a green marking under EditableGridView and the hint says: "the element EditableGridView is not known. The problem could be to a compilation error of the site or the file web.config is missing"
Any Help or idea Here?
Related
I cannot access Button b1 = sender as Button in page_load which is used in onclick Button. I want to use b1 of onclick button on page_load in asp.net c#.Note:Button is used in gridview. Please help me out. I will share my code below.
this is 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;
public partial class phoneLostData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button b1 = sender as Button;
try
{
string dbAddress = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\mca\sem5\sem5Project\App_Data\Database.mdf;Integrated Security=True;User Instance=True; MultipleActiveResultSets=True;";
SqlConnection myCon = new SqlConnection(dbAddress);
myCon.Open();
string q1 = "select complainerName,status from lostPhnFir";
SqlCommand myCmd = new SqlCommand(q1, myCon);
SqlDataReader readIt = myCmd.ExecuteReader();
while (readIt.Read())
{
// Response.Write("alert('hi')");
if (readIt["complainerName"].Equals("abc") && readIt["status"].Equals("Checked"))
{
b1.Text = "Checked";
b1.Enabled = false;
}
}
readIt.Close();
myCon.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
public void Button1(object sender, EventArgs e)
{
Button b1 = sender as Button; // I want to use this b1 to page_load
string dbAddress = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\mca\sem5\sem5Project\App_Data\Database.mdf;Integrated Security=True;User Instance=True; MultipleActiveResultSets=True;";
SqlConnection myCon = new SqlConnection(dbAddress);
myCon.Open();
string q1 = "select complainerName from lostPhnFir";
int flag = 0;
SqlCommand myCmd = new SqlCommand(q1, myCon);
SqlDataReader readIt = myCmd.ExecuteReader();
if (b1.ID == "btnFIRLodge")
{
b1.Text = "Checked";
b1.Enabled = false;
flag = 1;
}
if (flag == 1)
{
string status1 = "Checked";
string s1 = "abc";
string sql = "update lostPhnFir set status='" + status1 + "' where complainerName='" + s1 + "'";
SqlCommand myCmd2 = new SqlCommand(sql, myCon);
myCmd2.ExecuteNonQuery();
}
}
}
this is aspx.
<asp:TemplateField HeaderText="FIR Lodged" ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnFIRLodge" runat="server"
Text="Send Message" onclick="Button1"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
I am trying to pass a protected DataRow[] msgArray; from code-behind to the .net page.
msgArray contains rows from a DB table that I selected, when I do Response.Write(msgArray[0]["comment"]) it outputs correctly what I have stored in the comment column in my DB.
The problem is that I cannot do the same in my .net page when I load the page where I do this:
<asp:Panel ID="commentSection" runat="server">
<%= msgArray[0]["comment"] %>
</asp:Panel>
I get a Object reference not set to an instance of an object.
What am I doing wrong ?
This is my code-behind(.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;
using MySql.Data.MySqlClient;
namespace Groups
{
public partial class Group : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
String gname;
String gtype;
String uname;
DataTable group = new DataTable();
DataTable msg = new DataTable();
protected DataRow[] msgArray;
protected void Page_Load(object sender, EventArgs e)
{
String id = Request.QueryString["id"];
if (id != null)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT g.*, (SELECT COUNT(id) FROM app_groups.users_groups_leg ugl WHERE ugl.id_group = g.id) as member_count FROM app_groups.groups g WHERE g.id = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
group.Load(reader = cmd.ExecuteReader());
var groupArray = group.AsEnumerable().ToArray();
reader.Close();
int member_count = 0;
int.TryParse(groupArray[0]["member_count"].ToString(), out member_count);
Panel grInfo = new Panel();
grInfo.Controls.Add(new LiteralControl("<br/><div class='panel panel-primary'><div class='panel-heading'><h2>" + groupArray[0]["group_name"] + "</h2></div><div class='panel-body'><span>Categorie: <span class='title'>" + groupArray[0]["group_type"] + "</span></span><br/><span class='membrii'>" + (member_count == 1 ? member_count + " membru" : member_count + " membri") + "</span><br/><span>Fondat pe: " + ConvertUnixTimeStamp(groupArray[0]["founded"].ToString()) + "</span><br/></div></div>"));
groupInfo.Controls.Add(grInfo);
conn.Close();
showComments();
}
}
public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
return new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(unixTimeStamp) + 3600*2);
}
public DataRow[] showComments()
{
String id = Request.QueryString["id"];
if (id != null)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
msg.Load(reader = cmd.ExecuteReader());
msgArray = msg.AsEnumerable().ToArray();
reader.Close();
Response.Write(msgArray[0]["comment"]);
/*Panel grComments = new Panel();
grComments.Controls.Add(new LiteralControl(""));
groupInfo.Controls.Add(grComments);*/
}
return msgArray;
}
}
}
Create a new class dataAccess.cs
using System;
using System.Data;
namespace Groups
{
public class dataAccess
{
public List<string> GetComments()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
try
{
MySql.Data.MySqlClient.MySqlDataReader reader;
DataTable msg = new DataTable();
conn.Open();
List<string> comments = new List<string>();
queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
msg.Load(reader = cmd.ExecuteReader());
foreach(DataRow dr in msg.Rows)
{
comments.Add(dr["comment"]);
}
reader.Close();
return comments;
}
catch (Exception ex)
{
//throw ex;
}
}
}
}
In the ASPX page
<asp:Panel ID="commentSection" runat="server">
<%
var data = Groups.dataAccess.GetComments();
foreach(string c in data)
{
Response.Write("<p>" + c + "</p>");
}
%>
</asp:Panel>
According to ASP.NET Page Life cycle, your method showComments() will be called after the <%= msgArray[0]["comment"] %> part. Hence it won't be available there.
Best way is to have a control like Label in your .aspx page and update the text property from showComments() method.
I have a link button as follow
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx" runat="server">Recherche </asp:LinkButton>
i want get a query string from it
<asp:LinkButton ID="LinkButtonSearchClient" PostBackUrl="~/UI/clients.aspx?id=12" runat="server">Recherche </asp:LinkButton>
and the id value comes from the source code
public string ID
{
get { return ViewState["id"]; }
}
To get the value on page load (in the backend .cs file) :
protected void Page_Load(object sender, EventArgs e)
{
var id = Request.QueryString["id"];
if (id != null)
{
// use id
}
}
Or you might want to put the id into the link (in the html) :
<asp:LinkButton ID="LinkButtonSearchClient" runat="server"
NavigateUrl='<%# String.Format("~/UI/clients.aspx?id={0}", Eval("ID"))%>'
Text='Recherche'></asp:LinkButton>
You probably do not need a postback, look here : PostbackUrl vs NavigateUrl
Try this,
public string ID
{
get { Request.QueryString["id"]; }
}
Edit : In your page load set your postback url like this, access postbackurl in server side
LinkButtonSearchClient.PostBackUrl = "~/UI/clients.aspx?id=" + this.ID;
See my following example :
in design as follow
<asp:HyperLink ID="HLink" runat="server"
NavigateUrl='<%#"Mobiles_Details.aspx?ID=" + Eval("ID") %>' Text='<%#
Bind("Name") %>' Height="70px" Width="200px" Font-Bold="true" Font-
Size="10pt" Font-Names="Times New Roman" />
In coding the class Mobiles_Details is:
public partial class Mobiles_Details : System.Web.UI.Page
{
public string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
Session["UserID"] = "100";
//int ID = 102;
int ID = Convert.ToInt32(Request.QueryString["ID"].ToString());
Session["Product_ID"] = ID;
if (Session["UserID"] == null || Session["UserID"].ToString() == string.Empty)
{
Response.Redirect("Login.aspx", false);
}
else
{
if (ID != null)
{
DataTable dt = Load_Items_ID(Convert.ToInt32(Session["UserID"].ToString()), ID);
lbl_Name.Text = dt.Rows[0]["Name"].ToString();
lbl_Price.Text = dt.Rows[0]["Price"].ToString();
lbl_Details.Text = dt.Rows[0]["Details"].ToString();
img_Product.ImageUrl = dt.Rows[0]["image"].ToString();
}
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('An Error has been occured ');" + ex.ToString(), true);
}
}
}
public DataTable Load_Items_ID(int UserID, int ID)
{
DataTable Returned_Value = new DataTable();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Products where UserID= " + UserID + " and Status='False' and ID =" + ID))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(Returned_Value);
}
}
}
}
return Returned_Value;
}
}
i am working on an aspx website in which i am using a timer event.
i just want that timer should run when i click a specific button. now timer is running on page load. in Winforms we use timer.Tick() event to do it. but it is not supporting in website.
Can Anyone help me to sort this Out.
Thanks in Advance....
My Code is Here....
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;
using System.ComponentModel;
public partial class Expert : System.Web.UI.Page
{
public static BackgroundWorker worker = new BackgroundWorker();
protected void Page_Load(object sender, EventArgs e)
{
int id;
id = Int32.Parse(Request.QueryString["id"]);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlDataReader rd;
rd = new SqlCommand("Select * from ExpertChat where id=" + id, con).ExecuteReader();
rd.Read();
Image1.ImageUrl = rd["image1"].ToString();
Label8.Text = rd["image1"].ToString();
//Image3.ImageUrl = rd["image1"].ToString();
Label1.Text = rd["SName"].ToString();
Label2.Text = rd["Skills"].ToString();
Label5.Text = rd["rate"].ToString();
Label3.Text = rd["ReviewCount"].ToString();
Label4.Text = rd["Title"].ToString();
Label6.Text = rd["ReviewCount"].ToString();
Label7.Text = rd["Title"].ToString();
Label9.Text = rd["Qualification"].ToString();
Label10.Text = rd["MyServices"].ToString();
Label11.Text = rd["other"].ToString();
Label14.Text = rd["IsLoggedIn"].ToString();
int x = Int32.Parse(rd["IsLoggedIn"].ToString());
if (x == 1)
{
Image2.ImageUrl = "~/online.png";
}
else
{
Image2.ImageUrl = "~/offline.png";
}
rd.Close();
if (Session["User"] == "User")
{
SqlDataReader rd1 = new SqlCommand("Select funds from signup where email='" + Session["email"].ToString() + "'", con).ExecuteReader();
rd1.Read();
Label13.Text = rd1["funds"].ToString();
}
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
}
protected void SendButton_Click(object sender, EventArgs e)
{
string messageMask = "{0} # {1} : {2}";
string message = string.Format(messageMask, "yash", DateTime.Now.ToShortTimeString(), NewMessageTextBox.Text);
TextBox1.Text = TextBox1.Text + Environment.NewLine + message;
// Calling the DoWork Method Asynchronously
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myScript", "document.getElementById('" + NewMessageTextBox.ClientID + "').value = '';", true);
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
if (worker.IsBusy != true)
{
worker.RunWorkerAsync(new string[] { message, Label3.Text });
}
}
private static void DoWork(object sender, DoWorkEventArgs e)
{
string[] args = e.Argument as string[];
string value = args[0];
string id = args[1];
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("Update Chat set Data=#message,Updated1=1 where id=" + Int32.Parse(id), con);
cmd.Parameters.AddWithValue("#message", value);
cmd.ExecuteNonQuery();
con.Close();
}
protected void ChatTextTimer_Tick(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
//if (second1.Visible)
//{
// SqlDataReader rd7 = new SqlCommand("Select IsApproved from Chat where id=" + Int32.Parse(Label2.Text) + "'", con).ExecuteReader();
// rd7.Read();
// string str3 = rd7["IsApproved"].ToString();
// rd7.Close();
// if (str3 == "Approved")
// {
// second1.Visible = false;
// }
// else if (str3 == "Canceled")
// {
// second1.Visible = false;
// second3.Visible = true;
// }
//}
//else
//{
int x1 = 0;
SqlDataReader rd;
rd = new SqlCommand("Select UserInitial,Updated from Chat where id =" + Int32.Parse(Label3.Text), con).ExecuteReader();
rd.Read();
string str;
int i;
i = Int32.Parse(rd["Updated"].ToString());
if (i == 1)
{
str = rd["UserInitial"].ToString();
rd.Close();
x1 = x1 + 1;
TextBox1.Text = TextBox1.Text + Environment.NewLine + str;
SqlCommand
cmd = new SqlCommand("Update Chat set Updated=0 where id=" + Int32.Parse(Label3.Text), con);
cmd.ExecuteNonQuery();
}
else
{
rd.Close();
}
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (Session["User"] != "User")
{
Response.Redirect("signin.aspx");
}
else
{
if (Int32.Parse(Label13.Text) < 20)
{
Response.Redirect("Payment.aspx");
}
else
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LPSConnection"].ConnectionString.ToString());
con.Open();
SqlDataReader rd = new SqlCommand("Select Booked,email from ExpertChat where id=" + Request.QueryString["id"].ToString(), con).ExecuteReader();
rd.Read();
int x = Int32.Parse(rd["Booked"].ToString());
string str = rd["email"].ToString();
rd.Close();
if (x == 0)
{
//second1.Visible = true;
SqlDataReader mRead1, mRead3, mRead4;
mRead1 = new SqlCommand("insert into chat (ExpertName,UserName,rate,Data,Date,UserInitial) Values ('" + str + "','" + Session["SName"] + "','" + Label5.Text + "','Hello','" + DateTime.Now.ToShortDateString() + "','yash')", con).ExecuteReader();
mRead1.Close();
mRead3 = new SqlCommand("Update ExpertChat Set Booked=1 where SName='" + Label1.Text + "'", con).ExecuteReader();
mRead3.Close();
mRead4 = new SqlCommand("Select top 1 id from Chat where ExpertName='" + str + "' Order by id desc", con).ExecuteReader();
mRead4.Read();
int y = Int32.Parse(mRead4["id"].ToString());
mRead4.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "button1Clicked();", true);
ChatTextTimer.Enabled = true;
second3.Visible = false;
second1.Visible = false;
second2.Visible = false;
int id;
id = y;
Label3.Text = id.ToString();
SqlDataReader rd1 = new SqlCommand("Select ExpertName from Chat where id=" + y, con).ExecuteReader();
rd1.Read();
string str23 = rd1["ExpertName"].ToString();
rd1.Close();
SqlDataReader rd3;
rd3 = new SqlCommand("Select * from ExpertChat where email='" + str23 + "'", con).ExecuteReader();
rd3.Read();
string str2;
str2 = rd3["email"].ToString();
Label1.Text = rd3["rate"].ToString();
Image3.ImageUrl = rd3["image1"].ToString();
Label12.Text = rd3["rate"].ToString();
rd3.Close();
con.Close();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "TextBox1slide", "buttonClicked();", true);
//second2.Visible = true;
}
}
}
}
}
i want to run it when ImageButton1_Click event Fired....
If you're using Visual Studio 2010 up (correct me if I have my versions wrong) you should have access to Intellisense. You can use this to see all of your available methods.
Timer.Start()
http://msdn.microsoft.com/en-us/library/system.timers.timer.start(v=vs.110).aspx
How can I get the selected value from DetailsView to a textbox? So far I'm using this TextBox.Text = DetailsView1.SelectedValue.String(); But returns an error: Object reference not set to an instance of an object. I could do it in OnDataBound and ItemInserted in formview with no problem but this time I want to get the selected value from detailsview to paste it in a textbox on Page_Load event.
Help would be greatly appreciated. Thanks in advance!
Attached the rest of the code behind same code from my previous post:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LibraryManagementSystemC4.User
{
public partial class Reserving : System.Web.UI.Page
{
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["LibrarySystemConnectionString"].ConnectionString;
}
//string reservationid
private void ExecuteInsert(string bookid, string EmployeeID, string reservedate)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO BookReservation (bookid, EmployeeID, reservedate) VALUES " + " (#bookid, #EmployeeID, #reservedate)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
//param[0] = new SqlParameter("#reeservationid", SqlDbType.Int, 50);
param[0] = new SqlParameter("#bookid", SqlDbType.BigInt, 50);
param[1] = new SqlParameter("#EmployeeID", SqlDbType.NVarChar, 50);
param[2] = new SqlParameter("#reservedate", SqlDbType.DateTime, 10);
//param[0].Value = reservationid;
param[0].Value = bookid;
param[1].Value = EmployeeID;
param[2].Value = reservedate;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert error";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (bookidTextBox != null)
{
ExecuteInsert(bookidTextBox.Text, EmployeeIDTextBox.Text, reservedateTextBox.Value);
ClearControls(Page);
}
else
{
Response.Write("Please input ISBN");
bookidTextBox.Focus();
}
}
protected void Page_Load(object sender, EventArgs e)
{
{
bookidTextBox.Text = DetailsView1.SelectedValue.ToString();
EmployeeIDTextBox.Text = HttpContext.Current.User.Identity.Name.ToString();
}
}
public static void ClearControls(Control Parent)
{
if(Parent is TextBox)
{
(Parent as TextBox).Text = string.Empty;
}
else
{
foreach (Control c in Parent.Controls)
ClearControls(c);
}
}
}
}
DetailsView1.SelectedValue.String() will throw a null reference exception if SelectedValue is null, i.e. there is no selected value, which in the context of a DetailsView i think means it contains no data. You want to do:
if (DetailsView1.SelectedValue != null)
{
MyTextbox.Text = DetailsView1.SelectedValue.ToSTring();
}