2014-05-07 35 views
1

我有一个动态表,其中,在每一行我有一个文本框(txtCantitate)和一个按钮(btnMinus)。在文本框中,我有数量(int),并在按钮上单击我希望数量减少一。在这里,你有我在桌子上:动态表:链接按钮到文本框单元格

你能帮我做按钮的代码?问题是它是一个动态按钮...在每个记录上都有相同的ID ...我不知道该怎么做...

我在项目中使用的语言C#,.NET 4.5 ,js,jquery。

cell = new HtmlTableCell(); 
HtmlInputButton btnMinus = new HtmlInputButton(); 
btnMinus.ID = "btnMinus"; 
btnMinus.Value = "-"; 
cell.Controls.Add(btnMinus); 
row.Cells.Add(cell); 

cell = new HtmlTableCell(); 
HtmlInputText txtCantitate = new HtmlInputText(); 
txtCantitate.ID = "txtCantitate"; 
txtCantitate.Value = publicatie.Cantitate.ToString(); 
cell.Controls.Add(txtCantitate); 
row.Cells.Add(cell); 

回答

1

您需要在按钮中设置的点击事件,这将执行你的行动蚂蚁:

您将需要设置文本框和按钮的ID以匹配您在第一行中的行+单元格索引...因为这些是HtmlControls,所以您并没有真正的索引,因此您必须找到一种方法让这些在那里(我不会为你编码,对不起)。

btnMinus.ID = "btnMinus_" + CurrentRowIndex.ToString() + "_" + CurrentCellIndex.ToString(); 
txtCantitate.ID = "txtCantitate_" + CurrentRowIndex.ToString() + "_" + CurrentCellIndex.ToString(); 

那么你将不得不设置事件处理程序...

服务器端单击事件处理程序制定者(参见下面的实际事件处理程序代码):

btnMinus.Click += myButtonClick; 

客户端点击事件处理程序设置程序:

btnMinus.Attributes.Add("onclick","JavaScript:myButtonClick(this);"); 

如果您想要执行事件处理程序代码server-side:

private void myButtonClick(object sender, EventArgs e) 
{ 
    Button tmp = sender as Button; 
    string[] id = tmp.ID.Split(new string[]{"_"}, StringSplitOptions.None); 
    string textbox_ID = "txtCantitate" + "_" + id[1] + "_" + id[2]; 
    TextBox txt = this.Controls.FindControl(textbox_ID) as TextBox; 
    int val = -1; 
    string finaltext = ""; 
    if(int.TryParse(txt.Text, out val)) 
     finaltext = (val-1).ToString(); 
    else 
     finaltext = "Invalid number, Cannot decrement!"; 

    txt.Text = finaltext; 
} 

如果你想要做的事件处理程序代码客户端:

function myButtonClick(object sender) 
{ 
    //i'll let you figure this one out for yourself if you want to do it client-side, but it's very similar to the server-side one as far as logic is concerned... 
} 
+0

我想使用服务器端的形式给出,但“sender.ID.Split(新的String [] { “_”},StringSplitOptions.None);“没有工作,它不认可ID和Ideeas? – Andrew

+0

检查我刚刚在我的解决方案中发布的代码更改...你应该尝试玩它...可能是Id而不是ID ...等 – MaxOvrdrv

+0

该ID是解析好,忘了发布......但现在我有另一个问题... FindControl无法识别它总是为空;我试过: TextBox txt = this.Controls.FindControl(id)as TextBox; Control con = FindControl(id); TextBox txt = FindControl(id)as TextBox; HtmlInputText txt =(HtmlInputText)FindControl(id); 和什么都没有... – Andrew

1

这里是解决方案,

的Javascript

function MinusVal(ctrl) 
{ 
    var TextBox = $(ctrl).parent().next().find("input[type=text]"); 
    var Value = parseInt(TextBox.val()); 

    TextBox.val(Value - 1); 
    return false; 
} 

C#后端

btnMinus.Attributes.Add("onclick", "MinusVal(this);"); 
相关问题