我是一个网格视图,我可以编辑,更新,删除。我可以手动添加下拉列表并正确填充所选值,但我希望能够在编辑时填充数据库中的下拉列表(并正确显示所选值)。
我尝试了很多搜索/选项,但找不到让它工作的方法。
我的代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData();
lblMessage.Text = "";
}
string sSQL = "";
// populate drop downs
sSQL = @"SELECT ErrorTypeLookupID as Value, ErrorDescription as DisplayText
FROM BabelFish.dbo.ErrorTypeLookup (NOLOCK)
WHERE ErrorType = 'Category'
";
//ORDER BY OrderBy, ErrorDescription";
new DatabaseConnection().PopulateListBoxFromDB(sSQL, "", lstNewResolutionCategory);
sSQL = @"SELECT ErrorTypeLookupID as Value, ErrorDescription as DisplayText
FROM BabelFish.dbo.ErrorTypeLookup (NOLOCK)
WHERE ErrorType = 'Severity'
";
//ORDER BY OrderBy, ErrorDescription";
new DatabaseConnection().PopulateListBoxFromDB(sSQL, "", lstNewResolutionSeverity);
}//end page load
protected void DeleteRow(object sender, GridViewDeleteEventArgs e)
{
var ResolutionsID = GridView1.DataKeys[e.RowIndex].Value;
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
string sSQL = "Delete from BabelFish.dbo.Resolutions where ResolutionsID = @ResolutionsID";
SqlCommand sCommand = new SqlCommand(sSQL);
sCommand.Parameters.AddWithValue("@ResolutionsID", ResolutionsID);
// run delete
new DatabaseConnection().RSExecute(sCommand);
lblMessage.Text = "Record deleted successfully !";
GridView1.EditIndex = -1;
this.PopulateData();
}
protected void UpdateRow(object sender, GridViewUpdateEventArgs e)
{
var ResolutionsID = GridView1.DataKeys[e.RowIndex].Value;
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
TextBox txtResolutionDescription = row.FindControl("txtResolutionDescription") as TextBox;
DropDownList drpErrorCategoryID = row.FindControl("ErrorCategory") as DropDownList;
string sSQL = @"Update BabelFish.dbo.Resolutions set
ResolutionDescription = @ResolutionDescription,
UserIDSolved = ISNULL(BabelFish.dbo.fn_GetUserIDFromTeamMemberTable(@UserIDSolved), BabelFish.dbo.fn_GetUserIDFromTeamMemberTable(REPLACE(@UserIDSolved, '-', ''))),
DateTimeSolved = ISNULL(DateTimeSolved, GetDate())
where ResolutionsID = @ResolutionsID";
SqlCommand sCommand = new SqlCommand(sSQL);
sCommand.Parameters.AddWithValue("@ResolutionDescription", txtResolutionDescription.Text.Trim());
sCommand.Parameters.AddWithValue("@ResolutionsID", ResolutionsID);
sCommand.Parameters.AddWithValue("@UserIDSolved", UserID);
// run update
new DatabaseConnection().RSExecute(sCommand);
lblMessage.Text = "Record updated successfully !";
GridView1.EditIndex = -1;
this.PopulateData();
}
private void PopulateData()
{
string sSQL = @"SELECT
ResolutionsID, ErrorTableID, BabelFish.dbo.fn_GetUserNameFromTeamMemberTable(UserIDSolved) as UserIDSolved,
DateTimeSolved, ResolutionDescription, ResolutionCategory, ResolutionSeverity, IsActive
FROM BabelFish.dbo.Resolutions (NOLOCK)
Where ErrorTableID = '" + ErrorTableID + "'";
DataTable dt = DatabaseAccessing.DatabaseConnection.GetDataTable(sSQL);
// only do if more then 1 row exists
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
lblMessage.Text = "No Rows Exist.";
}
}
protected void AddRow(object sender, EventArgs e)
{
// get values to add to database
string txtResolutionDescription = txtNewResolutionDescription.Text.ToString();
string lstCategoryID = lstNewResolutionCategory.SelectedValue;
string lstSeverityID = lstNewResolutionSeverity.SelectedValue;
string sSQL = @"INSERT INTO BabelFish.dbo.Resolutions (
ErrorTableID, UserIDSolved, DateTimeSolved, ResolutionDescription,
ResolutionCategory, ResolutionSeverity, IsActive
)
VALUES (
@ErrorTableID, ISNULL(BabelFish.dbo.fn_GetUserIDFromTeamMemberTable(@UserIDSolved), BabelFish.dbo.fn_GetUserIDFromTeamMemberTable(REPLACE(@UserIDSolved, '-', ''))),
GetDate(), @ResolutionDescription,
@ResolutionCategory, @ResolutionSeverity, 1
)";
SqlCommand sCommand = new SqlCommand(sSQL);
sCommand.Parameters.AddWithValue("@ErrorTableID", ErrorTableID);
sCommand.Parameters.AddWithValue("@UserIDSolved", UserID);
sCommand.Parameters.AddWithValue("@ResolutionDescription", txtResolutionDescription);
sCommand.Parameters.AddWithValue("@ResolutionCategory", lstCategoryID);
sCommand.Parameters.AddWithValue("@ResolutionSeverity", lstSeverityID);
// run update
new DatabaseConnection().RSExecute(sCommand);
lblMessage.Text = "Record successfully added!";
GridView1.EditIndex = -1;
this.PopulateData();
}
protected void EditRow(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.PopulateData();
/*
//not working, ddl is NULL
var ddl = (DropDownList)GridView1.FindControl("selResolutionSeverity");
string sSQL = @"SELECT ErrorTypeLookupID as Value, ErrorDescription as DisplayText
FROM BabelFish.dbo.ErrorTypeLookup (NOLOCK)
WHERE ErrorType = 'Severity' ";
DataSet DS = new DatabaseAccessing.DatabaseConnection().DS(sSQL);
ddl.DataSource = DS;
ddl.DataTextField = "DisplayText";
ddl.DataValueField = "Value";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("-- Select --", "0"));
* */
}
protected void CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.PopulateData();
}
protected void ChangePage(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.PopulateData();
}
<asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
AutoGenerateColumns="false"
Width="100%"
OnRowEditing="EditRow"
OnRowCancelingEdit="CancelEditRow"
OnRowUpdating="UpdateRow"
DataKeyNames="ResolutionsID"
OnRowDeleting="DeleteRow"
AllowPaging="true"
PageSize="50"
OnPageIndexChanging="ChangePage"
>
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="ResolutionsID" DataField="ResolutionsID" ReadOnly="true" />
<asp:TemplateField HeaderText="ResolutionDescription">
<ItemTemplate><%# Eval("ResolutionDescription")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtResolutionDescription" runat="server" Text='<%# Eval("ResolutionDescription") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserIDSolved" DataField="UserIDSolved" ReadOnly="true" />
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
<%# Eval("ResolutionCategory")%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<EditItemTemplate>
<asp:DropDownList ID="selResolutionCategory" runat="server" SelectedValue='<%# Eval("ResolutionCategory") %>'>
<asp:ListItem Text="-- Select One --" Value="0" />
<asp:ListItem Text="cat1" Value="1" />
<asp:ListItem Text="cat2" Value="2" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Severity">
<ItemTemplate>
<%# Eval("ResolutionSeverity")%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<EditItemTemplate>
<asp:DropDownList ID="selResolutionSeverity" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to delete?')">
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#efefef" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
答案 0 :(得分:3)
您将要使用OnRowDataBound。以下是我在gridview中填充其中一个下拉列表的示例。
protected void gvVehicle_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow gvr in gvVehicleTEMP.Rows)
{
DropDownList ddlLocation = ((DropDownList)gvr.FindControl("ddlLocation"));
Label lblLocationLabel = ((Label)gvr.FindControl("lblLocationLabel"));
conn.Close();
conn.Open();
SqlCommand cmdLocationNames = new SqlCommand("SELECT Name FROM Billers WHERE Store = '" + 1 + "' ORDER BY Name ASC", conn);
List<string> internalLocationsList = new List<string>();
using (SqlDataReader reader = cmdLocationNames.ExecuteReader())
{
while (reader.Read())
{
string interlocations = reader.GetString(0);
internalLocationsList.Add(interlocations);
}
foreach (string locname in internalLocationsList)
{
ddlLocation.Items.Add(new ListItem(locname));
conn.Close();
}
conn.Close();
}
conn.Close();
}
//EDIT: if (lblLocationLabel.Text.Length > 0)
{
ddlLocation.SelectedValue = lblLocationLabel.Text;
}
}
所以,我使用了SqlDataReader,然后将“Billers”添加到列表中。一旦发生这种情况,我将listItems添加到下拉列表中。
我必须做的才能正确选择是将文本绑定到标签,然后说..
ddlLocation.SelectedValue = lblLabelLocation.Text;
不要忘记将OnRowDataBound放在gridview属性中。我希望这有帮助。
编辑:
这就是我做的。我使用if语句检查该标签的文本长度是否为空(我的下拉列表中有一个空白字段),如果它有文本,则选择或显示值..我在上面进行了编辑但是这里它又来了。
protected void gvVehicle_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow gvr in gvVehicleTEMP.Rows)
{
DropDownList ddlLocation = ((DropDownList)gvr.FindControl("ddlLocation"));
Label lblLocationLabel = ((Label)gvr.FindControl("lblLocationLabel")); //add this line to find the label
conn.Close();
conn.Open();
SqlCommand cmdLocationNames = new SqlCommand("SELECT Name FROM Billers WHERE Store = '" + 1 + "' ORDER BY Name ASC", conn);
List<string> internalLocationsList = new List<string>();
using (SqlDataReader reader = cmdLocationNames.ExecuteReader())
{
while (reader.Read())
{
string interlocations = reader.GetString(0);
internalLocationsList.Add(interlocations);
}
foreach (string locname in internalLocationsList)
{
ddlLocation.Items.Add(new ListItem(locname));
conn.Close();
}
conn.Close();
}
conn.Close();
}
if (lblLocationLabel.Text.Length > 0)//Added if statement
{
ddlLocation.SelectedValue = lblLocationLabel.Text;
}
}
我使用像这样的模板字段。
<asp:TemplateField HeaderText="Location" SortExpression="Received">
<ItemTemplate>
<asp:DropDownList ID="ddlLocation" runat="server" AutoPostBack="false">
</asp:DropDownList>
<asp:Label ID="lblLocationLabel" runat="server" Text='<%# Bind("Location") %>' Visible="false"></asp:Label>
<font size="2">Received On: </font>
</ItemTemplate>
<HeaderStyle Width="200px" />
</asp:TemplateField>
我希望这有点清除它。
答案 1 :(得分:0)
这里有几个问题:
selResolutionSeverity
和我建议您使用数据绑定来简化程序。如果您能够为严重性创建一个DataSource(例如SqlDataSource),那么您将不需要在代码中放置任何特定的逻辑。以下示例假设您的页面中有一个名为SqlDataSource
的{{1}}。如果您不希望沿着这条路线走下去,那么您也可以在RowDataBound事件处理程序中填充DropDownList。
dsSeverities
答案 2 :(得分:0)
您必须在DropDownList
GridViewRow
事件的修改模式中找到GridView
中的OnRowDataBound
。
以下是您可以这样做的方法:
在标记中为GridView
的OnDtatBound添加一个方法。 :
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
... ... ...
OnRowDataBound="GridView1_RowDataBound" >
现在在代码中编写你的GridView1_RowDataBound
方法编写这段代码(我强烈建议用参数化查询替换查询字符串以防止可能的sql注入):
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
//Make sure the row is in edit mode to find controls in EditItemTemlates
if ((e.Row.RowType == DataControlRowType.DataRow) && ((e.Row.RowState & DataControlRowState.Edit) > 0))
{
var ddl = GridView1.FindControl("selResolutionSeverity") as DropDownList;
if (ddl != null)
{
// Consider using parameterized query to prevent possible sql injection
string sSQL = @"SELECT ErrorTypeLookupID as Value, ErrorDescription as DisplayText
FROM BabelFish.dbo.ErrorTypeLookup (NOLOCK)
WHERE ErrorType = 'Severity' ";
DataSet DS = new DatabaseAccessing.DatabaseConnection().DS(sSQL);
ddl.DataSource = DS;
ddl.DataTextField = "DisplayText";
ddl.DataValueField = "Value";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("-- Select --", "0"));
}
}
}