我有一个数据表已经有一些值,而且它从下面的文本框中获取值。
现在我的问题是,当我不在文本框中输入值时,它仍然会进入数据表。 我不希望它这样做..
代码可以在任何机器上运行......任何建议????
由于
public partial class WebForm6 : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
// Initialize a DataTable
if (!Page.IsPostBack)
{
dt = new DataTable();
// Initialize DataColumn
DataColumn myDataColumn = new DataColumn();
//// initialize a new instance of DataColumn to add another column with different properties.
//myDataColumn = new DataColumn();
myDataColumn.ColumnName = "firstName";
// set DataType property of the column as String
myDataColumn.DataType = System.Type.GetType("System.String");
// Add and Create a Second DataColumn
dt.Columns.Add(myDataColumn);
// create a new row using NewRow() function of DataTable.
// dataRow object will inherit the schema of myDataTable to create a new row
DataRow dataRow = dt.NewRow();
dataRow["firstName"] = "John";
// add new data row to the data table.
dt.Rows.Add(dataRow);
// similarly adds the second row to the DataTable
dataRow = dt.NewRow();
dataRow["firstName"] = "Will";
dt.Rows.Add(dataRow);
Session["data"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Session["Data"] == null)
{
dt.Columns.Add("firstName");
BindtoGridViewFromTextBoxes(dt);
ClearControls();
}
else
{
dt = (DataTable)Session["Data"];
BindtoGridViewFromTextBoxes(dt);
ClearControls();
}
} private void ClearControls()
{
txtName.Text = String.Empty;
}
private void BindtoGridViewFromTextBoxes(DataTable dt)
{
DataRow dr;
dr = dt.NewRow();
dr["firstName"] = txtName.Text.ToString();
dt.Rows.Add(dr);
Session["Data"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
和.aspx页面
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<asp:TemplateField>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("firstName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("firstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
任何帮助.... ??
答案 0 :(得分:1)
将您的方法更改为:
private void BindtoGridViewFromTextBoxes(DataTable dt)
{
if (!String.IsNullOrEmpty(txtname.Text))
{
DataRow dr = dt.NewRow();
dr["firstName"] = txtName.Text;
dt.Rows.Add(dr);
Session["Data"] = dt;
}
GridView1.DataSource = dt;
GridView1.DataBind();
}