简体   繁体   中英

What is the best way to compare rows in a datalist

The general question I am asking is what is the best way to compare rows in a datalist. The code I have is about a datalist that contains a textbox and two buttons, one submit, and one clear. When the user clicks submit, I am trying to compare the textbox with the othter rows. The button click is a command and I am passing the ItemIndex as the command argument so I do know what row the button click is happening on. I am using a foreach loop to go through each row.

The following code is my foreach loop that is inside of my click event

int giftCount = 0;

foreach(DataListItem dli in dlGiftCode)
{
    bool isCurrentRow = dli.ItemIndex.ToString() == e.CommandArgument.ToString() ? true:false;
    int currentRow = Convert.ToInt32(e.CommandArgument);
    TextBox txtCardCode = (TextBox)giftcode.FindControl("txtCardCode");
    string currentCode = txtCardCode.Text;

    for(int x = 0; x < dlGiftCode.Items.Count; x++)
    {
        if(currentCode == txtCardCode.Text && !isCurrentRow)
            giftCount++;
    }

    if(giftCount <= 1)
    { 
        //Continue on
    }
    else
    {
        //show message
    }
}

The for loop is my failed attempt to find duplicates. I can see why it does not work but I just can't seem to get the correct logic on my issue. Could I make it a nested foreach using the same datalist and loop through each row again? Or is that not effective in what I am trying to achieve.

If anymore info is needed I can add it.

What you could do instead is first grab the DataListItem that was clicked, and find its TextBox:

LinkButton clickedButton = (LinkButton)sender;
DataListItem clickedItem = (DataListItem)clickedButton.NamingContainer;
TextBox clickedTextbox = (TextBox)clickedItem.FindControl("txtCardCode");

Then after that, iterate through the DataList's items, comparing the one you just clicked with the rest of them:

foreach (DataListItem dli in dlGiftCode.Items)
{
    if (dli != clickedItem)
    {
        TextBox tb = (TextBox)dli.FindControl("txtCardCode");
        if (tb.Text == clickedTextbox.Text)
        {
            giftCount++;            
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM