Button in GridView asp.net - asp.net

Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt=PrepareFirstGridViewRow(); //function below
DataRow dr = dt.NewRow();
dr["Index"] = index;
index++;
dr["Telephone"] = Telephone;
dr["Amount"] = Amount;
dr["Comment"] = Comment;
Button BTN = new Button();
BTN.Click += GridButton_Click;
BTN.OnClientClick = "GridButton_Click";
BTN.Text = "Sell";
BTN.Attributes.Add("CId", j.ToString());
BTN.Style.Value = "display:inline-block;";
BTNF.ButtonType = ButtonType.Button;
dr["Sell"] = BTN;
dt.Rows.Add(dr);
ContractsGrid.DataSource = dt;
ContractsGrid.DataBind();
ContractsGrid.Columns.Add(new DataControlField);
connection.Close();
}
And the function Prepare:
private DataTable PrepareFirstGridViewRow()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Index", typeof(string)));
dt.Columns.Add(new DataColumn("Telephone", typeof(string)));
dt.Columns.Add(new DataColumn("Amount", typeof(string)));
dt.Columns.Add(new DataColumn("Comment", typeof(string)));
dt.Columns.Add(new DataColumn("Sell", typeof(Button)));
return dt;
}
Everything works fine, except insertion of Buttons in last column, which do not appear at all (neither the header nor the button). When I replace ("Sell", typeof(Button)) with ("Sell", typeof(string)) and dr["Sell"] = "something"; the grid is created properly.
Question is simple: Why?
I tried the following solution:
protected void Page_Load(object sender, EventArgs e)
{
try
{
Button btn = new Button();
btn.Text = "Click";
btn.ID = "btn_click";
btn.Click += new EventHandler(btnevent_Click);
btn.OnClientClick = "Hello('" + "a" + "')";
form1.Controls.Add(btn);
}
catch (Exception)
{ }
}
And the above code produces buttons on the page event though it is in page_load event. So the problem must be not about the event, but the grid view.
Code below also works perfectly fine, but the button is added to whole grid (I am conscious about that). So it is not about the event but insertion of button into grid.
Button BTNo = new Button();
BTNo.Click += GridButton_Click;
BTNo.OnClientClick = "GridButton_Click";
BTNo.Text = "Sell";
BTNo.Attributes.Add("CId", "1");
BTNo.Style.Value = "display:block;";
ContractsGrid.DataSource = dt;
ContractsGrid.DataBind();
ContractsGrid.Controls.Add(BTNo);
connection.Close();

This is because of the asp.net page lifecycle. Controls are created before the"page_load" event. Try creating the button in an earlier event such as "page_init".

Solution is not to use datatable, gridview is also a bad idea, and my efforts to find the correct combination of lines of code were insufficient so i found a semi-solution: You can replace gridview with simple asp.net table component where you can put simply anthing. It does not resolve the problem the way I would like to, but it works and is clearer than datatables and binding it to gridviews.
Here is the working code:
TableRow tRow = new TableRow()
Tab.Rows.Add(tRow);
Tab.Rows.Add(tRow);
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
tCell.Text = "Row ";
Button bt = new Button();
bt.Text = "Click Me";
bt.OnClientClick = "TabButton_Click";
tCell.Controls.Add(bt);
tRow.Cells.Add(tCell);

Related

DevExpress GridView in LookUpEdit

I can add columns like this in GridView, but I don't know how to add RepositoryLookUpEdit. Would you help me with this topic? (I'm sorry for my bad English.)
DataTable DT = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
DT.Columns.Add("IP", Type.GetType("System.String"));
DT.Columns.Add("Port", Type.GetType("System.String"));
DT.Columns.Add("Username", Type.GetType("System.String"));
DT.Columns.Add("Password", Type.GetType("System.String"));
DT.Columns.Add("Working?", Type.GetType("System.Boolean"));
}
private void btn_ekle_Click(object sender, EventArgs e)
{
DataRow dr = DT.NewRow();
dr[0] = "Test";
dr[1] = "Test";
dr[2] = "Test";
dr[3] = "Test";
dr[4] = true;
DT.Rows.Add(dr);
dtg_goster.DataSource = DT;
gridView1.PopulateColumns();
You can modify the RepositoryItemLookUpEdit's Columns property to add/remove columns. This can be done at runtime:
lookUpEdit1.Properties.Columns.Add(new LookUpColumnInfo("FieldName", "Caption", 100)); //100 is width in pixels
Similar to what you are doing with the GridControl, you can also use the LookUpEdit's PopulateColumns method to create a column for each field in the data source. Note that you may need to also invoke the LookUpEdit's ForceInitialize method before you invoke the PopulateColumns method to ensure that the control is fully initialized.

Dynamically adding Table rows

I am trying to add values in table rows on button click. It's working on database but not working on web page. It override on last row on page.
How can I generate new row on every button click.
here is my button click code--
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//Label2.Visible = false;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CheckBox cb1 = new CheckBox();
I = Hidden1.Value;
I += 1;
cb1.ID = "cb1" + I;
TableRow Table1Row = new TableRow();
Table1Row.ID = "Table1Row" + I;
TableCell RCell1 = new TableCell();
RCell1.Controls.Add(cb1);
TableCell RCell2 = new TableCell();
RCell2.Text = txtName.Text;
tblLanguagesRow.Cells.Add(RCell1);
tblLanguagesRow.Cells.Add(RCell2);
tblLanguages.Rows.Add(tblLanguagesRow);
Hidden1.Value = I;
btnAdd.Visible = true;
btnDelete.Visible = true;
Label2.Visible = true;
Label2.Text = "Successfully Added";
add();
}
txtName.Text = "";
}
public int add()
{
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("hrm_AddLanguages", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#UpdatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#CreatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#UpdatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#IsDeleted", SqlDbType.Bit).Value = 0;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
Please Help me.
If possible try to do this using Grid view. It is better to use grid view instead of table.
Check out below link. It will help you to find your solution.
DataTable in ASP.Net Session

Add New Rows to GridView

I have a GridView on my page and on a button_OnClick event I'm wanting to add a new row to the grid.
I can add a row to the table using the following code, which works fine, but as I'm binding the DataTable to the grid any previous entries are lost.
string selectedProduct= ddlProducts.SelectedItem.Text;
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
So whilst I understand why this is causing the data loss, I'm not really sure how to get around it.
How can I add a new row to the GridView on each button click whilst retaining the previously added row? The data is not stored anywhere other than the grid itself, so there is no real datasource.
There are options such as Add row to gridview on client side which uses Jquery, but I have read that it isn't a great idea to use that when adding / removing items from the grid. Perhaps that is wrong? Or there is this Add new row to gridview but there isn't much detail there.
You need to store the Products into ViewState (or SessionState or Database) so that it can persist on post back.
For example,
private DataTable ProductDataTable
{
get { return ViewState["ProductDataTable"] as DataTable ?? new DataTable(); }
set { ViewState["ProductDataTable"] = value; }
}
protected void AddRowButton_Click(object sender, EventArgs e)
{
string selectedProduct = ddlProducts.SelectedItem.Text;
// Get the data from ViewState
DataTable dataTable = ProductDataTable;
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
// Save the data back to ViewState
ProductDataTable = dataTable;
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
}
Here is a sample you can try:
DataTable dt = new DataTable(); 
if (ViewState["CurrentTable"]!=null)
{
dt = (DataTable)ViewState["CurrentTable"];
  }
else
{
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
}
DataRow dr = null;            
dr = dt.NewRow();
dr["Col1"] = "tes";      
dr["Col2"] = "test";
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt; 
GridView1.DataSource = dt; 
GridView1.DataBind();
Sorry for bad formatting, typed this with my cellphone. Hope it helps! :-)
// OnButten click
function addrow(sender, args) {
// td add as per your column required
$("#GridView1 tbody").append('<tr><td>00001</td><td>Mr.</td><td>LOKESH N</td></tr>');
}

how to edit the gridview programatically in asp.net?

GridView gv = new GridView();
BoundField farmername = new BoundField();
farmername.HeaderText = "Farmer Name";
farmername.DataField = "farmername";
gv.Columns.Add(farmername);
BoundField villagename = new BoundField();
villagename.HeaderText = "Village Name";
villagename.DataField = "village";
gv.Columns.Add(villagename);
BoundField feedtype = new BoundField();
feedtype.HeaderText = "Feed Type";
feedtype.DataField = "feedtype";
gv.Columns.Add(feedtype);
BoundField bf50kg = new BoundField();
bf50kg.HeaderText = "50 Kg Bags";
bf50kg.DataField = "noof50kgsbags";
gv.Columns.Add(bf50kg);
CommandField cf = new CommandField();
cf.ButtonType = ButtonType.Button;
cf.ShowCancelButton = true;
cf.ShowEditButton = true;
gv.Columns.Add(cf);
gv.RowEditing += new GridViewEditEventHandler(gv_RowEditing);
gv.RowUpdating += new GridViewUpdateEventHandler(gv_RowUpdating);
gv.RowCancelingEdit += new GridViewCancelEditEventHandler(gv_RowCancelingEdit);
gv.AutoGenerateColumns = false;
gv.ShowFooter = true;
gv.DataSource = dtIndentDetails;
gv.DataBind();
When I clicked on edit button its not spliting into update, Cancel buttons . How can I do this with command field .If I add gridview in aspx page, its splitting to update and cancel
Try the following code:
protected void gridview_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView gv = (GridView)sender;
// Change the row state
gv.Rows[e.NewEditIndex].RowState = DataControlRowState.Edit;
}
Tried your code and found it working.
Take care of below points:
1.) The Code creating GridView (and all fields ) should be executed every time. Means remove any !IsPostback condition from this code, If present any.
2.) In your RowEditing event of your gridview set the editindex and rebind the gridview.
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView gv = sender as GridView;
gv.EditIndex = e.NewEditIndex;
gv.DataBind();
}

asp.net - GridView dynamic footer row creation problem

I am able to create BoundFields and Footer-rows dynamically like this in my GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CreateGridView();
}
}
private void CreateGridView()
{
GridView1.Columns.Clear();
DataTable dataTable = Book.GetBooksDataSet().Tables[0];
CommandField cf = new CommandField();
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
int colCount = 1;
foreach (DataColumn c in dataTable.Columns)
{
BoundField boundField = new BoundField();
boundField.DataField = c.ColumnName;
boundField.HeaderText = c.ColumnName;
//boundField.FooterText = "---";
if (colCount == 3 || colCount == 5)
{
boundField.ReadOnly = true;
}
GridView1.Columns.Add(boundField);
colCount++;
}
GridView1.ShowFooter = true;
GridView1.DataSource = dataTable;
GridView1.DataBind();
GridViewRow footerRow = GridView1.FooterRow;
Button b = new Button();
b.Text = "Add New";
int i = 0;
footerRow.Cells[i].Controls.Add(b);
foreach (DataColumn c in dataTable.Columns)
{
++i;
TextBox tb = new TextBox();
footerRow.Cells[i].Controls.Add(tb);
}
}
....................................
....................................
....................................
}
But the problem is, when I click the "Add New" - button, it disappears instantly. And, also I am unable to add any event handler to it. Or intercept its actions like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Edit")
{
GridView1.EditIndex = index;
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
//We can get cell data like this
string id = selectedRow.Cells[1].Text;
string isbn = selectedRow.Cells[2].Text;
//This is necessary to GridView to be showed up.
CreateGridView();
}
else if (e.CommandName == "Update")
{
LinkButton updateButton = (LinkButton)e.CommandSource;
DataControlFieldCell dcfc = (DataControlFieldCell)updateButton.Parent;
GridViewRow gvr = (GridViewRow)dcfc.Parent;
//The update...................
//Update grid-data to database
UpdateDataInTheDatabase(gvr.Cells[1].Controls);
//Grid goes back to normal
GridView1.EditIndex = -1;
//This is necessary to GridView to be showed up.
CreateGridView();
}
}
One more thing, I have seen some solutions that suggests to handle the GridView's rowBound event. But I need to do it from within Page_load event handler, or in, GridView1_RowCommand event handler.
Dynamically created controls mus be re-created on every postback. Your "Add New" button causes a postback so the dynamically created footer disappears. Is there a reason this grid has to be created dynamically? From the code you posted it appears that you could do this in markup instead. If not, you'll have to re-create the dynamic controls on every postback.
Edited to add:
I played with this a little bit and what's below works in that the grid doesn't disappear and events are handled, but it doesn't actually do anything. Hope this helps.
Markup:
<p><asp:Literal ID="Literal1" runat="server" /></p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowCommand="GridView1_RowCommand"
OnRowEditing="GridView1_RowEditing"/>
Code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private DataTable GetBooksDataTable()
{
var dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Author", typeof(string));
for (int index = 0; index < 10; index++)
{
dt.Rows.Add(index, "Title" + index, "Author" + index);
}
return dt;
}
private void BindGridView()
{
var dt = GetBooksDataTable();
GridView1.Columns.Clear();
GridView1.ShowFooter = true;
var cf = new CommandField();
cf.HeaderText = "Action";
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
for (int index = 0; index < dt.Columns.Count; index++)
{
var boundField = new BoundField();
boundField.DataField = dt.Columns[index].ColumnName;
boundField.HeaderText = dt.Columns[index].ColumnName;
GridView1.Columns.Add(boundField);
}
GridView1.DataSource = dt;
GridView1.DataBind();
var footer = GridView1.FooterRow;
var b = new LinkButton();
b.Text = "Add New";
b.CommandName = "Add New";
footer.Cells[0].Controls.Add(b);
for (int index = 1; index < dt.Columns.Count + 1; index++)
{
var tb = new TextBox();
footer.Cells[index].Controls.Add(tb);
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Literal1.Text = e.CommandName;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Literal1.Text = "Editing row index " + e.NewEditIndex.ToString();
}
Move your code from Page_Load to Page_Init. Things added in the Page_Load last only for the lifecycle of one postback.
You'd then be able to add eventhandlers, intercept events etc.

Resources