selected listbox items into database
HejHvordan får jeg ALLE valgte værdier fra min listbox over i databasen ? jeg kan ikke helt få mit loop til at virke...
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Define data objects
SqlConnection conn;
SqlCommand comm;
// Open the connection
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
// Initialize connection
conn = new SqlConnection(connectionString);
// Create command
comm = new SqlCommand("INSERT INTO TestTabel (TestNavn) VALUES (@TestNavn)",conn);
// Add command parameters
foreach (ListItem item in TestListBox.Items)
{
if (item.Selected)
{
comm.Parameters.Add("@TestNavn", System.Data.SqlDbType.NVarChar);
comm.Parameters["@TestNavn"].Value = item.Text;
}
}
// Enclose database code in Try-Catch-Finally
try
{
// Open the connection
conn.Open();
// Execute the command
comm.ExecuteNonQuery();
// Reload page if the query executed successfully
Response.Redirect("Default.aspx");
}
catch(Exception Arg)
{
Response.Write(Arg.Message);
// Display error message
Label1.Text = "Error !";
}
finally
{
// Close the connection
conn.Close();
}
}
}