Friday, March 16, 2012

Listbox control Problem

I am trying to insert all the values selected in a listbox into my database, but only one of the values actually gets inserted.

I know I need some sort of loop somewhere in order to accomplish this but I can't figure out where to place it.

See the code below for the Submit Button's click event that fires off the Insert Command:

Sub InsertRecord(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)

Dim strTitle as String = CType(e.Item.FindControl("add_Title"), TextBox).Text
Dim strCategory as ListBox = CType(e.Item.FindControl("add_DDL_Category"), ListBox)

Dim strSQL as String = "Insert Into Video (Title,Category) Values (@dotnet.itags.org.Title,@dotnet.itags.org.Category)"
MyConnection.Open()

Dim MyCommand as SqlCommand = new SqlCommand(strSQL, MyConnection)
MyCommand.CommandType = CommandType.Text

'Add Parameters to the SQL query
Dim parameterTitle as SqlParameter = new SqlParameter("@dotnet.itags.org.Title", SqlDbType.NVarChar, 255)
parameterTitle.Value = strTitle
MyCommand.Parameters.Add(parameterTitle)

Dim parameterCategory as SqlParameter = new SqlParameter("@dotnet.itags.org.Category", SqlDbType.NVarChar, 255)
parameterCategory.Value = strCategory.SelectedItem.Text
MyCommand.Parameters.Add(parameterCategory)

MyCommand.ExecuteNonQuery() 'Execute the UPDATE query
MyConnection.Close() 'Close the connection

'Rebind the DataGrid
dgDistro.EditItemIndex = -1
BindData()

End Sub

I probably loop throught the whole item collection of the list box, then only do the database operation on selected ones.

freach (ListItem liinthis.ListBox1.Items)

{

if (li.Selected ==true)

{

//populate parameters and execute command

}

}

Hop this help.


DavidDu:

if (li.Selected ==true)

li.Selected is bool already

if (li.Selected)
{

}


Can anyone convert this to VB.NET?

delobetc:

Can anyone convert this to VB.NET?

TryMSDN, there are a lot of samples.

0 comments:

Post a Comment