我正在使用asp.net 4.0 C#和Sql server 2008r2。
我找到并使用here中的代码创建带有文本框的gridview,并从here创建保存到我的数据库,稍作修改,如下所示。
我需要回忆一下数据库中的数据,并在gridview中填充动态创建的文本框。
我收到错误“在所选数据源上找不到名称'RowNumber'的字段或属性。”错误在Gridview.DataBind()行上;在Fillmygrid方法中。
如何为返回的每一行获取行。此列不在数据库中。
我目前的代码是:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
querytable();
}
}
protected void querytable()
{
string id = Session["ID"] as string;
using (SqlConnection con = new SqlConnection(connection string))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table WHERE column1 = @c1 AND column3 = 'A'", con))
cmd.Parameters.AddWithValue("@c1", id);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.hasRows)
{
FillGrid();
}
}
}
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
box1.Text = dt.Rows[i]["Column1"].ToString();
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dt.Rows.Add(dr);
dr = dt.NewRow();
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private void InsertRecords(StringCollection sc)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO SampleTable (Column1,Column2,Column3) VALUES";
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);
}
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
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)
{
string id = Session["ID"] as string;
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
string a = "A"
sc.Add(id + "," + box1.Text + "," + a);
rowIndex++;
}
InsertRecords(sc);
}
}
}
以下是问题代码: 将2更改为此代码:
private void fillmygrid()
{
string id = Session["ID"] as string;
//DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(connection string)
try
{
string cmd "Select column2 From table where column1 = '@c1' And column3 = 'A'";
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd, con);
da.SelectCommand.Parameters.AddWithValue("@c1", id);
DataSet ds = new DataSet();
da.Fill(ds);
if (dt.Rows.Count > 0)
{
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
}
catch (SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
Response.Write(msg);
}
finally
{
con.Close();
}
}
我的插入语句有效,我链接到相同的连接字符串。
感谢您的帮助。
答案 0 :(得分:0)
使用标准化方法,即SqlDataSource
绑定到GridView
控件(ASP.NET)。在线有大量样本,例如http://asp-net-example.blogspot.com/2008/12/aspnet-gridview-and-sqldatasource.html此解决方案允许您在SQL数据库中选择,删除或更新数据表。
为了添加(即插入)新记录,请使用FormView
(如有必要)。
的问候,