如何在保存到数据库之前显示唯一键异常?

时间:2015-06-16 08:35:04

标签: c# asp.net gridview drop-down-menu

我创建了一个gridview,用户可以在其中输入项目及其数量。项目数量未知,因此要求是能够添加用户想要的项目。所以我已经给出了为另一个条目添加项目行的规定。输入的所有这些数据都会进入一个临时表,只需点击一个按钮即可完成所有这些数据保存到数据库中。

在点击按钮之前,有没有办法隐藏上一行中已选择的项目,或者在选择下拉值时显示项目已经输入的错误。

我的gridview看起来像这样:

enter image description here

gridview代码:

<asp:GridView ID="gvItemList" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" CssClass="newStyle9" ForeColor="Black" OnRowDataBound="gvItemList_RowDataBound" OnRowDeleting="gvItemList_RowDeleting" ShowFooter="True" style="text-align: center" ViewStateMode="Enabled">
                                <Columns>
                                    <asp:TemplateField HeaderText="Sl No" SortExpression="Id">
                                        <ItemTemplate>
                                            <asp:Label ID="lblId" runat="server" Text="<%# Container.DataItemIndex+1 %>"></asp:Label>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Item Description">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px" AutoPostBack="True" OnSelectedIndexChanged="ddlItem_SelectedIndexChanged">
                                            </asp:DropDownList>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Unit">
                                        <ItemTemplate>
                                            <asp:Label ID="txtUnit" runat="server"></asp:Label>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Quantity">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtQty" runat="server" Height="27px" Width="73px"></asp:TextBox>
                                        </ItemTemplate>
                                        <FooterStyle HorizontalAlign="Right" />
                                        <FooterTemplate>
                                            <asp:Button ID="AddRowButton" runat="server" OnClick="ButtonAdd_Click" Text="Add New Item" />
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                </Columns>
                                <FooterStyle BackColor="#CCCCCC" />
                                <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                                <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
                                <RowStyle BackColor="White" />
                                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                                <SortedAscendingCellStyle BackColor="#F1F1F1" />
                                <SortedAscendingHeaderStyle BackColor="#808080" />
                                <SortedDescendingCellStyle BackColor="#CAC9C9" />
                                <SortedDescendingHeaderStyle BackColor="#383838" />
                            </asp:GridView>

代码背后:

private void SetInitialRowToGrid()
    {
        // Initialize and Set initial row of Datatable
        var tempDataTable = new DataTable();
        tempDataTable.Columns.Add("lblId");
        tempDataTable.Columns.Add("ddlItem");
        tempDataTable.Columns.Add("txtUnit");
        tempDataTable.Columns.Add("txtQty");        
        tempDataTable.Rows.Add("1", "", "", "");

        // Store that datatable into viewstate
        ViewState["TempTable"] = tempDataTable;

        // Attach Gridview Datasource to datatable        
        gvItemList.DataSource = tempDataTable;
        gvItemList.DataBind();
    }
    private void AddNewRowToGrid()
    {
        int rowIndex = 0;

        if (ViewState["TempTable"] != null)
        {
            // Get TempTable from viewstate
            var tempTable = (DataTable)ViewState["TempTable"];
            DataRow tempRow = null;

            if (tempTable.Rows.Count > 0)
            {
                for (int i = 1; i <= tempTable.Rows.Count; i++)
                {
                    // Get Grid's values
                    var Item =
                        (DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
                    var Unit =
                        (Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
                    var Qty =
                        (TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");


                    // Create new row and update Row Number
                    tempRow = tempTable.NewRow();

                    tempTable.Rows[i - 1]["ddlItem"] = Item.SelectedValue;
                    tempTable.Rows[i - 1]["txtUnit"] = Unit.Text;
                    tempTable.Rows[i - 1]["txtQty"] = Qty.Text;                    
                    rowIndex++;
                }

                // Add data to datatable and viewstate
                tempTable.Rows.Add(tempRow);
                ViewState["TempTable"] = tempTable;

                // Attach Gridview Datasource to datatable
                gvItemList.DataSource = tempTable;
                gvItemList.DataBind();
            }
        }

        //Set Previous Data on Postbacks
        SetPreviousData();
    }

    private void SetPreviousData()
    {
        int rowIndex = 0;

        if (ViewState["TempTable"] != null)
        {
            var tempTable = (DataTable)ViewState["TempTable"];

            if (tempTable.Rows.Count > 0)
            {
                for (int i = 0; i < tempTable.Rows.Count; i++)
                {
                    var Item =
                        (DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
                    var Unit =
                        (Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
                    var Qty =
                        (TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");


                    Item.SelectedValue = tempTable.Rows[i]["ddlItem"].ToString();
                    Unit.Text = tempTable.Rows[i]["txtUnit"].ToString();
                    Qty.Text = tempTable.Rows[i]["txtQty"].ToString();                   

                    rowIndex++;
                }
            }
        }
    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }
    protected void gvItemList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = Convert.ToInt32(e.RowIndex);

        deleteRow(index);
        SetPreviousData();        

        if (gvItemList.Rows.Count == 0)
        {
            SetInitialRowToGrid();
        }
    }
    private int deleteRow(int index)
    {
        int rowIndex = 0;

        if (ViewState["TempTable"] != null)
        {
            // Get TempTable from viewstate
            var tempTable = (DataTable)ViewState["TempTable"];


            if (tempTable.Rows.Count > 0)
            {
                for (int i = 1; i <= tempTable.Rows.Count; i++)
                {
                    // Get Grid's TextBox values
                    var Item =
                        (DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
                    var Unit =
                        (Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
                    var Qty =
                        (TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");
                }

                // Add data to datatable and viewstate                
                tempTable.Rows.RemoveAt(index);
                ViewState["TempTable"] = tempTable;

                // Attach Gridview Datasource to datatable
                gvItemList.DataSource = tempTable;
                gvItemList.DataBind();
            }
        }

        //Set Previous Data on Postbacks        
        return index;
    }

    protected void gvItemList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlItem = (e.Row.FindControl("ddlItem") as DropDownList);
            Jilu1TableAdapters.tbl_ItemTableAdapter item;
            item = new Jilu1TableAdapters.tbl_ItemTableAdapter();
            DataTable dt = new DataTable();
            dt = item.GetItems();

            ddlItem.DataSource = dt;
            ddlItem.DataTextField = "Item";
            ddlItem.DataValueField = "Item";
            ddlItem.DataBind();
            ddlItem.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--Select an Item--", "0"));
        }
    }
    private void InsertRecords(StringCollection sc)
    {
        Jilu1TableAdapters.tbl_Jr_BOMTableAdapter ds;
        ds = new Jilu1TableAdapters.tbl_Jr_BOMTableAdapter();

        StringBuilder sb = new StringBuilder(string.Empty);
        string[] splitItems = null;
        string user = Page.User.Identity.Name;

        try
        {
            foreach (string item in sc)
            {


                if (item.Contains(",,,"))
                {
                    //To prevent null reference error
                }
                else
                {
                    splitItems = item.Split(",".ToCharArray());
                    ds.InsertJrBOM(ddlState.SelectedValue, ddlDistrict.SelectedValue, ddlCluster.SelectedValue, ddlSiteID.SelectedValue, txtSiteName.Text, ddlSiteType.SelectedValue, txtNoBTS.Text, txtNoLinks.Text, txtLoadBand.Text, ddlEBAvailability.SelectedValue, txtEBPhase.Text, txtDGCapacity.Text, txtDGPhase.Text, splitItems[0], splitItems[1], splitItems[2], user, DateTime.Now, "Nil", 1, txtDispatch.Text);

                }

            }
            lblSuccess.Visible = true;
            lblSuccess.Text = "Records Successfully Saved!";
            Timer1.Enabled = true;
        }
        catch (System.Data.SqlClient.SqlException)
        {
            lblErrorMessage.Visible = true;
            lblErrorMessage.Text = "Duplicate Items has been entered, please correct it before proceeding or an entry for " + ddlSiteID.Text + " has already made, please go to edit page to make necessary changes!";
             Timer1.Enabled = true;
            return;
        }
        catch (Exception ex)
        {
            lblErrorMessage.Visible = true;
            lblErrorMessage.Text = "Error: " + ex.Message;
            Timer1.Enabled = true;
        }        

    }    
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        int rowIndex = 0;
        StringCollection sc = new StringCollection();
        if (ViewState["TempTable"] != null)
        {

            DataTable dtCurrentTable = (DataTable)ViewState["TempTable"];
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    DropDownList ddlItem = (DropDownList)gvItemList.Rows[rowIndex].Cells[2].FindControl("ddlItem");
                    Label txtUnit = (Label)gvItemList.Rows[rowIndex].Cells[3].FindControl("txtUnit");
                    TextBox txtQty = (TextBox)gvItemList.Rows[rowIndex].Cells[4].FindControl("txtQty");

                    //get the values from the TextBoxes
                    //then add it to the collections with a comma "," as the delimited values
                    sc.Add(ddlItem.SelectedValue + "," + txtUnit.Text + "," + txtQty.Text);
                    if (sc.Contains(",,,"))
                    {
                        lblErrorMessage.Visible = true;
                        lblErrorMessage.Text = "Fields should not be left empty!";
                        Timer1.Enabled = true;
                        return;
                    }
                    else
                    {
                        string Quantity = txtQty.Text;
                        float num;
                        if (float.TryParse(Quantity, out num))
                        {
                            rowIndex++;
                        }
                        else
                        {
                            lblErrorMessage.Visible = true;
                            lblErrorMessage.Text = "Quantity field must be a number!";
                            Timer1.Enabled = true;
                            return;
                        }
                    }
                }
                //Call the method for executing inserts
                InsertRecords(sc);
                if (lblSuccess.Text == "Records Successfully Saved!")
                {
                    this.SetInitialRowToGrid();
                    string user = Page.User.Identity.Name;
                    StatusTableAdapters.tbl_NotificationsTableAdapter ds2;
                    ds2 = new StatusTableAdapters.tbl_NotificationsTableAdapter();

                    ds2.InsertNotification(ddlSiteID.SelectedValue, "BOM Notification", DateTime.Now, user, "Role6");

                }
            }
        }
    }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

protected void ddlItem_SelectedIndexChanged(object sender, EventArgs e)
{
     var main = (sender as DropDownList);

     foreach (GridViewRow row in gvItemList.Rows)
     {
           var ddl = (row.FindControl("ddlItem") as DropDownList);

           if (main.ClientID != ddl.ClientID && ddl.SelectedValue == main.SelectedValue)
           {
                row.BackColor = System.Drawing.Color.Red;
                string script = "alert('already selected!');";
                ScriptManager.RegisterStartupScript(this, GetType(), 
                  "ServerControlScript", script, true);
           }
     }         
}