Reputation: 1
I wrote this code to update a field in database but this field isn't updated.
I think the problem is related the find control cause I try that and it couldn't find my control.
C# code:
protected void btnCh_Click(object sender, EventArgs e)
{
SqlConnection db = new SqlConnection(strcon);
foreach (RepeaterItem repeaterItem in Repeater1.Items)
{
CheckBox CheckBox1 = (CheckBox)repeaterItem.FindControl("CheckBox1");
if (CheckBox1.Checked)
{
db.Open();
Label mylbl = (Label)repeaterItem.FindControl("mylbl");
string mm= mylbl.Text;
SqlCommand MyCMD = new SqlCommand("Update BuyGem Set GemChargeStatuse=1 ,Apple_gmail_Pass='' WHERE ID=@ID");
MyCMD.Parameters.AddWithValue("@ID", mm);
MyCMD.ExecuteNonQuery();
db.Close();
}
}
}
Aspx code:
<div class="col-md-12">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="col-md-12">
<div class=" pull-right col-sm-6 animated2 bounceInLeft">
<div class="panel panel-primary ">
<asp:Label ID="mylbl" runat="server" ><%#Eval("ID")%></asp:Label>
<div class="panel-body" dir="rtl">
Name :
<asp:Label ID="lblname" runat="server"><%#Eval("Name") %></asp:Label>
<br />
<div class="col-md-9 pull-left col-xs-12 top15">
select:
<asp:CheckBox ID="CheckBox1" runat="server" />
</div>
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnCh" runat="server" Text="Button" OnClick="btnCh_Click" />
</div>
I should tell that the problem is not related to update command.I have tested and found out that the problem is related to findconrol that can't find any control in my repeater.please review your answers.
Upvotes: 0
Views: 103
Reputation: 91
MyCMD isn't associated with the db connection. Use something like:
var MyCMD = db.CreateCommand();
Upvotes: 0
Reputation: 4630
replace
SqlCommand MyCMD = new SqlCommand("Update BuyGem Set GemChargeStatuse=1 ,Apple_gmail_Pass='' WHERE ID=@ID");
MyCMD.Parameters.AddWithValue("@ID", mm);
to
SqlCommand MyCMD = new SqlCommand("Update BuyGem Set GemChargeStatuse=1 ,Apple_gmail_Pass='' WHERE ID=@ID",db);
MyCMD.Parameter.Add("@ID",SqlDbType.Int).Value=mm;
see Difference between Parameters.Add and Parameters.AddWithValue
Upvotes: 1
Reputation: 401
Is your ID parameter in the Database a varchar or integer? Because currently
SqlCommand MyCMD = new SqlCommand("Update BuyGem Set GemChargeStatuse=1 ,Apple_gmail_Pass='' WHERE ID=@ID");
MyCMD.Parameters.AddWithValue("@ID", mm);
you are searching by string, where you shold be converting the string to integer like so:
int.Parse(idStringHere);
Upvotes: 0