Reputation: 1445
I have a CheckBoxList control and update button:
<asp:CheckBoxList ID="moduleselect" runat="server" DataSourceID="semester2" DataTextField="module_name" DataValueField="module_id"></asp:CheckBoxList>
<br />
<asp:Button ID="uploadbutton" runat="server" Text="Choose Modules" OnClick="uploadbutton_Click" CssClass="submitbtn" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" CssClass="submitbtn" />
This contains a list of modules for students to choose and when the upload button is clicked then it should update a database table.
I have the following C#
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String name = Request.QueryString["studentno"];
username.Text = name;
}
protected void uploadbutton_Click(object sender, EventArgs e)
{
String user = username.Text;
string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(ConnectionString);
myConnection.Open();
int count = moduleselect.Items.Count;
for (int i = 0; i < count; i++)
{
if (moduleselect.Items[i].Selected)
{
string value = moduleselect.Items[i].Value;
String query = "INSERT INTO students_vs_modules (student_no, module_id) VALUES (@student_no, @module_id)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@student_no", user);
myCommand.Parameters.AddWithValue("@module_id", value);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
}
}
}
However, when I select a number of modules when the upload button is clicked it only updates the initial option selected and not all of them. I'm pretty new to web development so any help would be greatly appreciated.
Upvotes: 0
Views: 1478
Reputation: 1024
First you need loop to get checked value for the checkbox
. Using SelectedValue
will only get the first value
you selected
For example as per below
int count = moduleselect.Items.Count;
for(int i = 0; i < count; i++)
{
if (moduleselect.Items[i].Selected)
{
string value = moduleselect.Items[i].Value;
// Do Insert
}
}
This will insert a lot of line with different module..
If you want to add in 1 line and separate by ,
As per below
int count = moduleselect.Items.Count;
string value = string.Empty;
for(int i = 0; i < count; i++)
{
if (moduleselect.Items[i].Selected)
{
value = moduleselect.Items[i].Value + ",";
}
}
// Trim the last ,
value = value.TrimEnd(',');
// Insert here
Upvotes: 2