如何在单个记录asp .net中将多个checklistbox保存到数据库 [英] how to save multiple checklistbox to database in a single record asp .net
问题描述
我有两个复选框列表CandidateName和Payment,以及一个下拉列表。用户可以在复选框列表中进行多项选择,在下拉列表中进行一次选择。我将chechboxlists和dropdownlist的数据填充到嵌套在具有gridview和此面板的UpdatePanel内的Panel。当我点击Add Button打开Panel时,所有数据都会填充。当我尝试通过for循环保存选定的复选框列表时,它无法正常工作。当我在for循环语句中调试时,它不会进入循环内部。如何使循环工作以便它将保存在数据库中。请帮我指教。谢谢
这是我的C#代码。
protected void btnAddNew_Click( object sender,EventArgs e)
{
尝试
{
string strcbl1 = string 跨度> .Empty;
string strcbl2 = string .Empty;
compCon = new SqlConnection(strConnectionString);
compCon.Open();
for ( int i = 0 ; i < cblCandidateName1.Items.Count-1; i ++)
{
if (cblCandidateName1.Items [i] .Selected == true )
{
strcbl1 = strcbl1 + cblCandidateName1.Items [i] .Value.ToString()+ ,;
}
}
for ( int j = 0 ; j < cblPayment1.Items.Count - 1 ; j ++)
{
if (cblPayment1.Items [j] .Selected == true )
{
strcbl2 + = cblPayment1.Items [j] .Value.ToString()+ < span class =code-string>,;
}
}
string strCourseID = ddlCourseName.Item.SelectedItem.Value.ToString();
string InsertSchedule = INSERT INTO ScheduleEmail(CANDIDATE_ID,PAYMENT_ID,TEMPLATE_ID)VALUES(@strCID,@ strPID,@ sqCourseID);
SqlCommand InsertScheduleCommand = new SqlCommand(InsertSchedule,compCon);
InsertScheduleCommand.Connection = compCon;
InsertScheduleCommand.Parameters.AddWithValue( @ strCID ,strcbl1);
InsertScheduleCommand.Parameters.AddWithValue( @ strPID,strcbl2);
InsertScheduleCommand.Parameters.AddWithValue( @ strCourseID,strCourseID);
InsertScheduleCommand.ExecuteNonQuery();
compCon.Close();
}
catch (例外情况)
{
ShowPopUpMsg( 数据无法保存在表格中。请联系您的系统管理员\ n + ex.ToString());
}
最后
{
DispalyGridViewScheduleEmail();
compCon.Close();
}
}
这是我的html代码。
< asp:Panel ID = panelAddNewTitle runat = server style = cursor:move; font-family:Tahoma; padding:2px; HorizontalAlign = 中心 < span class =code-attribute> BackColor = 蓝色 ForeColor = 白色 高度 = 25 > 添加新 < / asp:面板 > < ajaxToolkit:ModalPopupExtender ID = mpe1 runat = server TargetControlID = btnAddNew1 PopupControlID = panelAddNew RepositionMode = RepositionOnWindowResizeAndScroll < span class =code-attribute> DropShadow = true PopupDragHandleControlID = panelAddNewTitle BackgroundCssClass = modalBackground > < / ajaxToolkit:ModalPopupExtender >
< asp:CheckBoxList < span class =code-attribute> ID = cblCandidateName1 runat = server RepeatColumns = 3 RepeatDirection = 水平 RepeatLayout = table >
< asp:CheckBoxList ID = cblPayment1 runat = server RepeatDirection = 水平 RepeatLayout = 表 > < / asp: CheckBoxList >
< asp:DropDownList ID = ddlCourseName runat = 服务器 >
< asp:按钮 ID = btnAddNew2 runat = server 宽度 = 70 文字 = 添加 OnClick = btnAddNew_Click ValidationGroup = 添加 / >
< asp:按钮 ID = btnCancel1 runat = server 宽度 = 70 文字 = 取消 CausesValidation = false OnClick = Cancel_Click ValidationGroup = 添加 / >
< / div >
< / asp:Panel >
不知道为什么你为什么停止列表之外的一个项目计数。
您应该替换此代码
for ( int i = 0 ; i < cblCandidateName1.Items.Count- 1 ; i ++)
{
if (cblCandidateName1.Items [i] .Selected == true )
{
strcbl1 = strcbl1 + cblCandidateName1.Items [i] .Value.ToString()+ 跨度>;
}
}
with
foreach ( object checkedItem in cblCandidateName1.CheckedItems)
{
strcbl1 + = 字符串 .Format( {0 },,checkedItem.ToString());
}
您可能还应该在将字符串添加到数据库之前对其进行修剪
< pre lang =c#> InsertScheduleCommand.Parameters.AddWithValue( @ strCID,strcbl1.TrimEnd( ' ,'));
也就是说,将一个逗号分隔的字符串添加到数据库的列是一个非常糟糕的设计。如果你规范化数据库,你可能会更好。
在这种情况下,列表框中的每个项目都对应一个单独表格中的一行。
维基百科:数据库规范化 [ ^ ]
数据库规范化基础知识 [ ^ ]
3普通表格数据库教程 [ ^ ]
insted of loop使用此代码。 。 。这个是升然后循环..
var selectedValues = checkedItem.Items.Cast< listitem>()
.Where (li => li.Selected)
.Select(li => li.Value)
.ToArray();< / listitem>
我猜你是从<$ c中的代码动态添加项目到CheckBoxList
$ c>页面加载活动。
您检查过IsPostBack
吗?我想你没有。
I have two checkboxlists CandidateName and Payment, and a dropdownlist. User can do multiple selections in checkboxlists and one selection at dropdownlist. I am populating those data of chechboxlists and dropdownlist to Panel nested inside UpdatePanel which has gridview and this panel. When I click on Add Button to open up Panel, all data is populating. When I tried to save selected checkedbox lists through "for loop", it is not working. When I debug at for loop statement, it is not going inside the loop. How can I have loop working so that it will save in database. Please help me advise. Thank
This is my C# code.
protected void btnAddNew_Click(object sender, EventArgs e)
{
try
{
string strcbl1 = string.Empty;
string strcbl2 = string.Empty;
compCon = new SqlConnection(strConnectionString);
compCon.Open();
for (int i = 0; i < cblCandidateName1.Items.Count-1; i++)
{
if (cblCandidateName1.Items[i].Selected ==true)
{
strcbl1 = strcbl1 + cblCandidateName1.Items[i].Value.ToString() + ",";
}
}
for (int j = 0; j < cblPayment1.Items.Count - 1; j++)
{
if (cblPayment1.Items[j].Selected == true)
{
strcbl2 += cblPayment1.Items[j].Value.ToString() + ",";
}
}
string strCourseID = ddlCourseName.Item.SelectedItem.Value.ToString();
string InsertSchedule = "INSERT INTO ScheduleEmail(CANDIDATE_ID, PAYMENT_ID, TEMPLATE_ID)VALUES(@strCID, @strPID, @strCourseID)";
SqlCommand InsertScheduleCommand = new SqlCommand(InsertSchedule, compCon);
InsertScheduleCommand.Connection = compCon;
InsertScheduleCommand.Parameters.AddWithValue(@"strCID", strcbl1);
InsertScheduleCommand.Parameters.AddWithValue(@"strPID", strcbl2);
InsertScheduleCommand.Parameters.AddWithValue(@"strCourseID", strCourseID);
InsertScheduleCommand.ExecuteNonQuery();
compCon.Close();
}
catch (Exception ex)
{
ShowPopUpMsg("Data is failed to save in table. Please contact your system administrator \n" + ex.ToString());
}
finally
{
DispalyGridViewScheduleEmail();
compCon.Close();
}
}
This is my html code.
<asp:Panel ID="panelAddNewTitle" runat="server" style="cursor:move;font-family:Tahoma;padding:2px;" HorizontalAlign="Center" BackColor="Blue" ForeColor="White" Height="25" >Add New</asp:Panel><ajaxToolkit:ModalPopupExtender ID="mpe1" runat="server" TargetControlID="btnAddNew1" PopupControlID="panelAddNew" RepositionMode="RepositionOnWindowResizeAndScroll" DropShadow="true" PopupDragHandleControlID="panelAddNewTitle" BackgroundCssClass="modalBackground" ></ajaxToolkit:ModalPopupExtender>
<asp:CheckBoxList ID="cblCandidateName1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" RepeatLayout="table">
<asp:CheckBoxList ID="cblPayment1" runat="server" RepeatDirection="Horizontal" RepeatLayout="Table"></asp:CheckBoxList>
<asp:DropDownList ID="ddlCourseName" runat="server">
<asp:Button ID="btnAddNew2" runat="server" Width="70" Text="Add" OnClick="btnAddNew_Click" ValidationGroup="add"/>
<asp:Button ID="btnCancel1" runat="server" Width="70" Text="Cancel" CausesValidation="false" OnClick="Cancel_Click" ValidationGroup="add"/>
</div>
</asp:Panel>
Not sure why you are why you stop one item short of the list count.
You should replace this code
for (int i = 0; i < cblCandidateName1.Items.Count-1; i++) { if (cblCandidateName1.Items[i].Selected ==true) { strcbl1 = strcbl1 + cblCandidateName1.Items[i].Value.ToString() + ","; } }
with
foreach (object checkedItem in cblCandidateName1.CheckedItems) { strcbl1 += String.Format("{0},", checkedItem.ToString()); }
You should probably also trim the string before adding it to the database
InsertScheduleCommand.Parameters.AddWithValue(@"strCID", strcbl1.TrimEnd(','));
That said, it is a pretty bad design to add comma separated string to a column to a database. You would probably be better of if you normalized your database.
In such a case, each item in the listbox would correspond to one row in a separate table.
Wikipedia: Database normalization[^]
Database Normalization Basics[^]
3 Normal Forms Database Tutorial[^]
Insted of loop Use this code . . .this one is liter then loop..
var selectedValues = checkedItem.Items.Cast<listitem>() .Where(li => li.Selected) .Select(li => li.Value) .ToArray();</listitem>
I guess you are dynamically adding items toCheckBoxList
from code inPage Load
Event.
Have you checkedIsPostBack
? I guess you have not.
这篇关于如何在单个记录asp .net中将多个checklistbox保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!