且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将文本框中的数据绑定到datagridview?

更新时间:2023-02-20 15:52:05

将此添加到您的代码中后

受保护的List< Control> listOfControls;

受保护的字符串GetTextValue()
{


TextBox textbox =(TextBox)Page.FindControl("textbox");
返回textbox.Text;
}


受保护的void Button1_Click(对象发送者,EventArgs e)
{

//您可以对此进行改进,但您可以理解,这将更改第三行的单元格
//对于第一行执行1等操作,应将其重构
TextBox txt =(TextBox)FindControlRecursive(GridView1,"mygrdviewtext",3);

txt.DataBind();
}

公共控件FindControlRecursive(控件根,字符串ID,整数行)
{


listOfControls = new List< Control>();

FindControlRecursive(Root,Id);

返回listOfControls [row -1];
}


公共控件FindControlRecursive(控件根,字符串ID)
{
如果(Root.ID == Id)
{
listOfControls.Add(Root);
}

foreach(Root.Controls中的Control Ctl)
{
控件FoundCtl = FindControlRecursive(Ctl,Id);

如果(FoundCtl!= null)
{
listOfControls.Add(FoundCtl);

}
}

返回null;
}


//在aspx页面中,将这样的内容添加到gridview中的单元格所在的位置,再次对它进行更改.
Add this to your code behind

protected List<Control> listOfControls;

protected string GetTextValue()
{


TextBox textbox = (TextBox)Page.FindControl("textbox");
return textbox.Text;
}


protected void Button1_Click(object sender, EventArgs e)
{

// you can improve this but you can get the idea, this would change the cell on row three
// for row one do 1 etc, this should be re-factored
TextBox txt = (TextBox)FindControlRecursive(GridView1, "mygrdviewtext",3);

txt.DataBind();
}

public Control FindControlRecursive(Control Root, string Id, int row)
{


listOfControls = new List<Control>();

FindControlRecursive(Root, Id);

return listOfControls[row -1];
}


public Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
{
listOfControls.Add(Root);
}

foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);

if (FoundCtl != null)
{
listOfControls.Add(FoundCtl);

}
}

return null;
}


// in your aspx page add something like this to your gridview , where the cell is, again change as it applies to you.

<asp:TemplateField HeaderText="fromtextbox">
               <ItemTemplate>
                           <asp:TextBox ID="mygrdviewtext" runat="server" Text='<%# GetTextValue() %>' />
                </ItemTemplate>
               </asp:TemplateField>


您可以在DataGrid_EditCommand中控制验证,也可以在单元格上进行客户端验证.如果仅使用gridview显示数据,那么为什么在填写表单后不更新数据库中的值,然后刷新gridview.您是说不想更新数据库,而只是将值从文本框传输到gridview中的单元格吗?那么您为什么不在文本框的文本更改事件中执行此操作.标准解决方案通常是***的.
You can control the validation in DataGrid_EditCommand or else put client side validation on the cells. If you are only using the gridview to display data, then why don''t you update the values in the database after your form is filled out and then refresh the gridview. Are you saying you don''t want to update the database and just transfer the value from the textbox to a cell in the gridview? then why don''t you do that in the text changed event of the textbox. standard solutions are usually the best.