我想只插入選定的值,但當我保存它將所有值插入數據庫。 如何避免將不需要的值插入數據庫?
在上面的數據庫subject
列中,我只想要有能力的主題。但在我的數據庫中所有主題都插入了。
我使用boundfield
作爲GridView
中的主題欄。我的代碼到目前爲止`
<asp:GridView ID="Gvassignsubject" runat="server" AutoGenerateColumns="False" OnRowDataBound="Gvassignsubject_RowDataBound">
<Columns>
<asp:BoundField DataField="Subject" HeaderText="subject" SortExpression="subject" />
<asp:TemplateField HeaderText ="Faculty">
<ItemTemplate>
<asp:Label ID ="lblfaculty" runat="server" Text='<%%# Eval("facultyname") %>>' Visible="false"/>
<asp:DropDownList ID="ddlfaculty" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Set Hour">
<ItemTemplate>
<asp:TextBox ID="txthour" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
protected void btnsubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
foreach (GridViewRow r in Gvassignsubject.Rows)
{
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
string batch = ddlbatches.SelectedValue;
string subject = r.Cells[0].Text;
DropDownList ddlfaculty = (DropDownList)Gvassignsubject.Rows[i].FindControl("ddlfaculty");
TextBox txthour = (TextBox)Gvassignsubject.Rows[i].FindControl("txthour");
string facultyname = ddlfaculty.SelectedValue;
string sethour = txthour.Text;
con2.Open();
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(@batch,@facultyname,@sethour,@subject)", con2);
cmd.Parameters.AddWithValue("@batch", batch);
cmd.Parameters.AddWithValue("@subject", subject);
cmd.Parameters.AddWithValue("@facultyname", facultyname);
cmd.Parameters.AddWithValue("@sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
con2.Close();
}
}
}
}
能否請您把支票ddlfaculty.SelectedValue一樣,如果(!(ddlfaculty.SelectedValue.ToString()==「請選擇」) –