如何将DetailsView中的选定值添加到文本框中?到目前为止,我正在使用此TextBox.Text = DetailsView1.SelectedValue.String();
但返回错误:对象引用未设置为对象的实例。我可以在FormView中的OnDataBound和ItemInserted中做到没有问题,但这次我想从detailsview中获取选定的值,将其粘贴到Page_Load事件的文本框中。
非常感谢帮助。提前谢谢!
将其余代码附加在我之前发布的相同代码后面:
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);
}
}
}
}
答案 0 :(得分:2)
DetailsView1.SelectedValue.String()
将抛出一个空引用异常,即没有选中的值,在DetailsView的上下文中,我认为它意味着它不包含任何数据。你想做的事:
if (DetailsView1.SelectedValue != null)
{
MyTextbox.Text = DetailsView1.SelectedValue.ToSTring();
}