The issue is I am using 2 gridviews on two different forms; the first one is to display items from a database and it working fine. When I select a row and click a button, the row will go to gridview #2 on the second form "Shopping Cart Form" I will display the row, but when I close the form or when I select another row from gridview #1 and want to retrieve it the first row that has been retrieved will be replaced by the new select row! how i can keep all the select item in gridview 2?
Here is the code for Grid View 1
private void Buyer_Main_Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-CJGIQ74;Initial Catalog=Items;Integrated Security=True");
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM list", con);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int n = Gridview.Rows.Add();
Gridview.Rows[n].Cells[0].Value = item[0].ToString();
Gridview.Rows[n].Cells[1].Value = item["Name"].ToString();
Gridview.Rows[n].Cells[2].Value = item["Price"].ToString();
Gridview.Rows[n].Cells[3].Value = item["Quantity"].ToString();
}
}
The code of the button to retrieve items to Gridview 2
private void button1_Click_1(object sender, EventArgs e)
{
Checkout datagrid = new Checkout(Gridview.SelectedRows[0].Cells[0].Value.ToString(),
Gridview.SelectedRows[0].Cells[1].Value.ToString(),
Gridview.SelectedRows[0].Cells[2].Value.ToString(),
Gridview.SelectedRows[0].Cells[3].Value.ToString());
datagrid.Show();
}
GridView 2 to display retrieved items
public Checkout(string ID, string name, string price , string quantity)
{
InitializeComponent();
dataGridView1.Rows.Add();
dataGridView1.Rows[0].Cells[0].Value = ID;
dataGridView1.Rows[0].Cells[1].Value = name;
dataGridView1.Rows[0].Cells[2].Value = price;
dataGridView1.Rows[0].Cells[3].Value = quantity;
}
So basically I want to keep retrieved data in grid-view 2 so the user can select what he want to purchase and checkout the selected items. Also, can anyone help me about the quantity how can I select only one it will be subtracted from inventory or stock I have
First GridView
<asp:GridView ID="gvAll" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true"
OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "CustomerID" HeaderText = "Customer ID"
HtmlEncode = "false" />
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name"
HtmlEncode = "false" />
<asp:BoundField DataField = "City" HeaderText = "City"
HtmlEncode = "false" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
Secondary GridView
<asp:GridView ID="gvSelected" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" EmptyDataText = "No Records Selected" >
<Columns>
<asp:BoundField DataField = "CustomerID" HeaderText = "Customer ID" />
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
<asp:BoundField DataField = "City" HeaderText = "City" />
</Columns>
</asp:GridView>
private void BindGridone()
{
string constr = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
string query = " select CustomerID, ContactName, City from customers";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
sda.Fill(dt);
gvAll.DataSource = dt;
gvAll.DataBind();
}
The GetData function simply retrieves the records for which the user has checked the checkbox, adds them to a DataTable and then saves the DataTable to ViewState
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords"] != null)
dt = (DataTable)ViewState["SelectedRecords"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gvAll.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < gvAll.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gvAll.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
}
else
{
dt = RemoveRow(gvAll.Rows[i], dt);
}
}
}
ViewState["SelectedRecords"] = dt;
}
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("CustomerID");
dt.Columns.Add("ContactName");
dt.Columns.Add("City");
dt.AcceptChanges();
return dt;
}
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["CustomerID"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["ContactName"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["City"] = gvRow.Cells[3].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("CustomerID = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GetData();
gvAll.PageIndex = e.NewPageIndex;
BindGridone();
SetData();
}
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindGridtwo();
}
private void BindGridtwo()
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
Related
i retrieve gridview from database. but i change the structure of gridview. it different display from database which is i put the row in database become column in gridview. but the column i want for example Date|A|B|C|D but i get in gridview like this Date|B|D|A|C|. the B|D|A|C i retrieve from column prod_line in database. how to rearrange it back ? this is my code :
protected void Page_Load(object sender, EventArgs e)
{
//where request_date >= DATEADD(day,-8, GETDATE())
con.Open();
DataTable dtTemp = new DataTable();
cmd = new SqlCommand("SELECT request_date,prod_line,jo_no,qty,CONVERT(VARCHAR(10),need_by_date ,101) as need_by_date FROM CutPanelCard order by request_date", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtTemp);
con.Close();
ViewState["Information"] = dtTemp;
try
{
con.Open();
{
//DataTable dtTemp = (DataTable)ViewState["Information"];
DataTable dtDistinctRecords = dtTemp.DefaultView.ToTable(true, "prod_line");
DataTable dtStudentName = dtTemp.DefaultView.ToTable(true, "request_date");
DataTable a = new DataTable();
DataTable dtStudent = new DataTable();
dtStudent.Columns.Add("request_date");
foreach (DataRow rows in dtDistinctRecords.Rows)
{
dtStudent.Columns.Add(rows["prod_line"].ToString());
}
foreach (DataRow row in dtStudentName.Rows)
{
DataRow dr = dtStudent.NewRow();
dr["request_date"] = row["request_date"];
DataView dv = new DataView(dtTemp);
dv.RowFilter = "request_date='" + row["request_date"] + "'";
DataTable dtStudentdtl = dv.ToTable();
for (int i = 0; i < dtStudentdtl.Rows.Count; i++)
{
string colValue = dtStudentdtl.Rows[i]["jo_no"].ToString();
string colValue2 = dtStudentdtl.Rows[i]["qty"].ToString();
string colValue3 = dtStudentdtl.Rows[i]["need_by_date"].ToString();
dr[dtStudentdtl.Rows[i]["prod_line"].ToString()] = "JO: " + colValue + " Quantity: " + colValue2 + " Need by Date: " + colValue3 ;
}
dtStudent.Rows.InsertAt(dr, dtStudent.Rows.Count);
}
GridView1.DataSource = dtStudent;
GridView1.DataBind();
//GridView_Row_Merger(GridView1);
GridView_Row_Merger(GridView1);
con.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
I'm guessing you are using AutoGenerated Columns. So the easiest way would be to rearrange your query. The first column you select will be the first in the GridView.
SELECT jo_no, qty, request_date, prod_line ...
That will change the order in the GridView. However I suggest you start using TemplateFields. You have much more control over the Grid layout and design.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<%# Eval("prod_line") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<%# Eval("qty") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have two grid views :
gvdetails and
gvTranferRows
gvdetails are bind from selected database. The fields are :
id,
moduleName and
Item fields.
In gvTransferRows fields are :
id,
ModuleName,
Item and
BatchNo.
BatchNo is selected from dropdownlist.
But I want to transfer selected rows from gvdetails to gvTranferRows.
In this process I successfully remove and add gvdetails selected rows to gvTranferRows by clicking remove button at same time and vice versa.
But after clicking the remove button it done and again same operation to second time clicking the add button the gvdetails gridview will completely remove it transfer to gvTransferRows.
What I need is to select second time in add button, it will not remove only selected values remove and transfer to second gridview.
This is the code I tried for code :
.aspx:
<table align="center">
<tr>
<td class="auto-style2"></td>
<td class="auto-style1">
<asp:DropDownList ID="ddlbatchno" runat="server" Height="16px" Width="131px">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="auto-style2"></td>
</tr>
<tr>
<td class="auto-style2" valign="top">
<asp:GridView ID="gvDetails" runat="server" DataKeyNames="ModuleName" AutoGenerateColumns="false" CellPadding="5">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" />
<asp:BoundField DataField="ModuleName" HeaderText="ModuleName" />
<asp:BoundField DataField="Item" HeaderText="Item" />
<asp:BoundField DataField="BatchNo" HeaderText="BatchNo" />
</Columns>
<HeaderStyle BackColor="#6699ff" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</td>
<td class="auto-style1">
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="ADD" />
<br />
<label>
>><br />
<br />
</label>
<br />
<asp:Button ID="btnRemove" runat="server" OnClick="btnRemove_Click" Text="Remove" />
<br />
<label>
<<</label> </td>
<td valign="top">
<asp:GridView ID="gvTranferRows" runat="server" DataKeyNames="ModuleName" AutoGenerateColumns="false" CellPadding="5" EmptyDataText="No Records Found">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect2" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" />
<asp:BoundField DataField="ModuleName" HeaderText="ModuleName" />
<asp:BoundField DataField="Item" HeaderText="Item" />
<asp:BoundField DataField="BatchNo" HeaderText="BatchNo" />
</Columns>
<HeaderStyle BackColor="#6699ff" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<br />
</td>
</tr>
</table>
.cs page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlbatch();
BindGridview();
BindSecondGrid();
}
}
public void ddlbatch()
{
SqlCommand cmd1 = new SqlCommand("Select BatchNo from Batches", con);
cmd1.CommandType = CommandType.Text;
cmd1.Connection = con;
con.Open();
ddlbatchno.DataSource = cmd1.ExecuteReader();
ddlbatchno.DataTextField = "BatchNo";
ddlbatchno.DataBind();
con.Close();
ddlbatchno.Items.Insert(0, new ListItem("--Select batche no--", "0"));
}
protected void BindGridview() //Binding gvDetaails gridview
{
SqlDataAdapter da = new SqlDataAdapter("select id,ModuleName,Item,BatchNo from ModuleItems", con);
DataTable dt = new DataTable();
da.Fill(dt);
ViewState["dt"] = dt;
ViewState["dt1"] = dt;
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
protected void BindSecondGrid() // binding gvtransfer gridview
{
DataTable dt = (DataTable)ViewState["GetRecords"];
gvTranferRows.DataSource = dt;
gvTranferRows.DataBind();
}
string name;
protected void btnAdd_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvDetails.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkSelect") as CheckBox);
if (chkRow.Checked)
{
int totalCount = gvDetails.Rows.Cast<GridViewRow>().Count(r => ((CheckBox)r.FindControl("chkSelect")).Checked);
name += row.Cells[1].Text + ",";
}
}
}
string[] name3 = name.Split(',');
for (int l = 0; l < name3.Length; l++)
{
string str = "UPDATE ModuleItems SET BatchNo = " + ddlbatchno.SelectedItem.ToString() + " WHERE id= '" + name3[l] + "'";
SqlCommand cmd = new SqlCommand(str, con);
con.Open();
int j = cmd.ExecuteNonQuery();
con.Close();
}
foreach (GridViewRow oItemLeft in gvDetails.Rows)
{
if (((CheckBox)oItemLeft.FindControl("chkSelect")).Checked)
{
GetSelectedRows();
BindSecondGrid();
break;
}
}
DataTable dt = ViewState["dt"] as DataTable; //2nd time adding gvdetails to gvtransfer dt will become null
if (dt != null)
{
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow row = dt.Rows[i];
string dtname = row["id", DataRowVersion.Original].ToString();
string[] name1 = name.Split(',');
for (int l = 0; l < name1.Length; l++)
{
string name2 = name1[l].ToString();
if (dtname == name2)
{
row.Delete();
}
}
}
}
ViewState["dt"] = dt;
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
private void GetSelectedRows()
{
DataTable dt;
if (ViewState["GetRecords"] != null)
dt = (DataTable)ViewState["GetRecords"];
else
dt = CreateTable();
for (int i = 0; i < gvDetails.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvDetails.Rows[i].Cells[0].FindControl("chkSelect");
if (chk.Checked)
{
dt = AddGridRow(gvDetails.Rows[i], dt);
}
}
ViewState["GetRecords"] = dt;
}
private DataTable CreateTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("ModuleName");
dt.Columns.Add("Item");
dt.Columns.Add("BatchNo");
dt.AcceptChanges();
return dt;
}
private DataTable AddGridRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
int rowscount = dt.Rows.Count - 1;
dt.Rows[rowscount]["id"] = gvRow.Cells[1].Text;
dt.Rows[rowscount]["ModuleName"] = gvRow.Cells[2].Text;
dt.Rows[rowscount]["Item"] = gvRow.Cells[3].Text;
dt.Rows[rowscount]["BatchNo"] = ddlbatchno.SelectedItem.Text;
dt.AcceptChanges();
}
return dt;
}
protected void btnRemove_Click(object sender, EventArgs e)
{
if (gvTranferRows.Rows.Count > 0)
{
foreach (GridViewRow row in gvTranferRows.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow1 = (row.Cells[0].FindControl("chkSelect2") as CheckBox);
if (chkRow1.Checked)
{
int totalCount = gvTranferRows.Rows.Cast<GridViewRow>().Count(r => ((CheckBox)r.FindControl("chkSelect2")).Checked);
name += row.Cells[1].Text + ",";
}
}
}
string[] name3 = name.Split(',');
foreach (GridViewRow oItemLeft in gvTranferRows.Rows)
{
if (((CheckBox)oItemLeft.FindControl("chkSelect2")).Checked)
{
GetRemoveRows();
BindGridview();
//break;
}
}
DataTable dt = ViewState["dt"] as DataTable;
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow row = dt.Rows[i];
string dtname = row["id", DataRowVersion.Original].ToString();
string[] name1 = name.Split(',');
for (int l = 0; l < name1.Length; l++)
{
string name2 = name1[l].ToString();
if (dtname != name2)
{
row.Delete();
}
}
}
ViewState["dt"] = dt;
gvTranferRows.DataSource = dt;
gvTranferRows.DataBind();
}
}
DataTable dt,dt1;
private void GetRemoveRows()
{
if (ViewState["GetRecords"] != null)
dt = (DataTable)ViewState["GetRecords"];
ViewState["GetRecords"] = dt;
ViewState["GetRecords2"] = dt;
gvDetails.DataSource = dt;
gvDetails.DataBind();
this. ViewState.Remove("GetRecords2"); //for viewstate control
ViewState["GetRecords2"] = null;//for variables
}
I am attaching my result image how the result will process. I posted full of my code can anyone please help me out.
use a temporary DataTable to maintain the list selected rows or records and then use the DataTable to bind the secondary GridView.
U will get more idea from here
Transfer Selected Rows from one GridView to Another in Asp.net
Another way to transfer data
Please try DataTable.ImportRow method:
DataTable.ImportRow() on MSDN
I'm using this method on many WebForms and MVC pages and it works great.
I'm getting this error whenever I try to bind data inside gridview dropdownlist.
Here is the aspx code:
<asp:TemplateField HeaderText="Item Description" SortExpression="ddlItem">
<ItemTemplate>
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px" SelectedValue='<%# Eval("ddlItem") %>'>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Here is the code behind (c#):
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(); //Here I'm getting the error.
}
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"));
}
}
protected void ddlSiteID_SelectedIndexChanged(object sender, EventArgs e)
{
Jilu1TableAdapters.tbl_Jr_BOMTableAdapter ds;
ds = new Jilu1TableAdapters.tbl_Jr_BOMTableAdapter();
DataTable dt = new DataTable();
dt = ds.GetVersion(ddlSiteID.SelectedValue);
ddlVersion.DataSource = dt;
ddlVersion.DataValueField = "Version";
ddlVersion.DataTextField = "Version";
ddlVersion.DataBind();
int ver = Convert.ToInt32(ddlVersion.Text);
DataTable dt1 = new DataTable();
dt1 = ds.GetDetails(ddlSiteID.SelectedValue, ver);
foreach (DataRow row in dt1.Rows)
{
txtSiteName.Text = (row["txtSiteName"].ToString());
ddlSiteType.Text = (row["ddlSiteType"].ToString());
txtNoBTS.Text = (row["txtNoBTS"].ToString());
txtNoLinks.Text = (row["txtNoLinks"].ToString());
txtLoadBand.Text = (row["txtLoadBand"].ToString());
ddlEBAvailability.Text = (row["ddlEBAvailability"].ToString());
txtEBPhase.Text = (row["txtEBPhase"].ToString());
txtDGCapacity.Text = (row["txtDGCapacity"].ToString());
txtDGPhase.Text = (row["txtDGPhase"].ToString());
}
gvItemList.DataSource = dt1;
gvItemList.DataBind();
}
I tried putting Text = 'Bind("ddlItem")', Datasourse, SelectedValue but still no luck.
Any help will be greatly appreciated.
In this code ,
<asp:DropDownList ID="ddlItem" runat="server" Height="25px" Width="200px"
SelectedValue='<%# Eval("ddlItem") %>'>
</asp:DropDownList>
you set SelectedValue to '<%# Eval("ddlItem") %>' but ddlItem is not exist in your datasource fields .
Put the correct field which you want to display in your dropdownlist .
And I suggest you to set DataTextField and DataValueField of your DropDownList .
Set it like DataTextField="ddlItem" DataValueField="ddlItem" .
Hope it's help for you :)
Your way is wrong
try this below way
protected void gvItemList_RowDataBound(object sender, GridViewEditEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("ddlItem");
//bind dropdownlist
DataTable dt = con.GetData("select * from tablename");//selected data from db or anywhere for bind ddl
ddList.DataSource = dt;
ddList.DataTextField = "YourCOLName";//id
ddList.DataValueField = "YourCOLName";//displaying name
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
ddList.SelectedValue = dr["YourCOLName"].ToString();// default selected value
}
}
}
I want to add a new blank row to the gridview after binding as seen in the picture when clicking the link button below. The textboxes inside the gridview should remain the same if there is any data entered in it. I just want to add one row.
you can try the following code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("PayScale", typeof(string));
dt.Columns.Add("IncrementAmt", typeof(string));
dt.Columns.Add("Period", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = TextBox1.Text;
NewRow[1] = TextBox2.Text;
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
}
here payscale,incrementamt and period are database field name.
You can run this example directly.
aspx page:
<asp:GridView ID="grd" runat="server" DataKeyNames="PayScale" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Pay Scale">
<ItemTemplate>
<asp:TextBox ID="txtPayScale" runat="server" Text='<%# Eval("PayScale") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Increment Amount">
<ItemTemplate>
<asp:TextBox ID="txtIncrementAmount" runat="server" Text='<%# Eval("IncrementAmount") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Period">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" Text='<%# Eval("Period") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />
C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grd.DataSource = GetTableWithInitialData(); // get first initial data
grd.DataBind();
}
}
public DataTable GetTableWithInitialData() // this might be your sp for select
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
table.Rows.Add(1, "David", "1");
table.Rows.Add(2, "Sam", "2");
table.Rows.Add(3, "Christoff", "1.5");
return table;
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
DataTable dt = GetTableWithNoData(); // get select column header only records not required
DataRow dr;
foreach (GridViewRow gvr in grd.Rows)
{
dr = dt.NewRow();
TextBox txtPayScale = gvr.FindControl("txtPayScale") as TextBox;
TextBox txtIncrementAmount = gvr.FindControl("txtIncrementAmount") as TextBox;
TextBox txtPeriod = gvr.FindControl("txtPeriod") as TextBox;
dr[0] = txtPayScale.Text;
dr[1] = txtIncrementAmount.Text;
dr[2] = txtPeriod.Text;
dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
}
dr = dt.NewRow(); // add last empty row
dt.Rows.Add(dr);
grd.DataSource = dt; // bind new datatable to grid
grd.DataBind();
}
public DataTable GetTableWithNoData() // returns only structure if the select columns
{
DataTable table = new DataTable();
table.Columns.Add("PayScale", typeof(string));
table.Columns.Add("IncrementAmount", typeof(string));
table.Columns.Add("Period", typeof(string));
return table;
}
protected void TableGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1 && e.Row.RowType == DataControlRowType.Header)
{
GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.DataRow,DataControlRowState.Insert);
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = " ";
gvRow.Cells.Add(tCell);
Table tbl = e.Row.Parent as Table;
tbl.Rows.Add(gvRow);
}
}
}
try using the cloning technique.
{
DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
// then for each of the values use a loop like below.
int cc = yourdatagrid.Columns.Count;
for (int i2 = 0; i < cc; i2++)
{
row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
}
yourdatagrid.Rows.Add(row);
i++;
}
}
This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.
If you are using dataset to bind in a Grid, you can add the row after you fill in the sql data adapter:
adapter.Fill(ds);
ds.Tables(0).Rows.Add();
I'm trying eventually to sort the gridview, But when I convert:
DataTable dt = (DataTable)gridAllTests.DataSource;
There's an exeption - can't convert object DateTime to String.
The datasource comes from database sql server, using Entity
GridView:
<asp:GridView ID="gridAllTests" runat="server" AutoGenerateColumns="false"
DataKeyNames="testId" AllowSorting="true">
<Columns>
<asp:BoundField DataField="courseName" HeaderText="Course" SortExpression="courseName"/>
<asp:BoundField DataField="onDate" HeaderText="Date" SortExpression="onDate"
DataFormatString="{0:d}" HtmlEncode="false"/>
<asp:BoundField DataField="lastRegisterDate" HeaderText="LastDate"
SortExpression="lastRegisterDate" DataFormatString="{0:d}" HtmlEncode="false"/>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnRegister" runat="server" text="Register"
CommandName="Register" CommandArgument='<%#Eval("testId") %>' />
<asp:Literal ID="litAlreadyRegisterd" runat="server" Text="Registered"/>
<asp:Literal ID="litTooLate" runat="server" Text="Registration Over"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
SecondTestEntities1 db = new SecondTestEntities1();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
User currUser = (User)Session["user"];
gridAllTests.DataSource = from test in db.Tests
select new
{
testId= test.TestId,
courseName = test.Course.Name,
onDate = test.OnDate,
lastRegisterDate = test.LastRegisterDate
};
try
{
gridAllTests.DataBind();
DataTable dt = (DataTable)gridAllTests.DataSource;
Session["taskTable"] = dt;
}
catch (Exception err)
{
lblError.Text = err.Message.ToString();
}
}
if (gridAllTests.Rows.Count < 1)
{
lblMessage.Visible = true;
}
}
Try this way
DataView dv=(DataView) from test in db.Tests
select new
{
testId= test.TestId,
courseName = test.Course.Name,
onDate = test.OnDate,
lastRegisterDate = test.LastRegisterDate
};
gridAllTests.DataSource = dv;
DataTable dt = new DataTable();
DataSourceSelectArguments args = new DataSourceSelectArguments();
DataView dv = new DataView();
dv = (DataView)dv.Select(args);// This SqlDataSourceObject means your sql query return object ,like dataset or dataview, etc
dt = dv.ToTable();
Try converting your date objects to strings
test.OnDate.ToString(//format here);
test.LastRegisterDate.ToString(//format here);
I think I've come across a similar issue where DataTable doesn't know how to deal with DateTime objects.
if (!Page.IsPostBack)
{
User currUser = (User)Session["user"];
// Dataset dsGrdDource = new Dataset();
IEnumerable<DataRow> result = from test in db.Tests
select new
{
testId= test.TestId,
courseName = test.Course.Name,
onDate = test.OnDate.ToShortDateString() ,
lastRegisterDate = test.LastRegisterDate
};
DataTable dtgrdSource= query.CopyToDataTable<DataRow>();
try
{
gridAllTests.DataSource =dtgrdSource;
gridAllTests.DataBind();
// DataTable dt = (DataTable)dsGrdDource.Tables[0];
Session["taskTable"] = dtgrdSource;
}
catch (Exception err)
{
lblError.Text = err.Message.ToString();
}
}
If you are using ToShortDateString() do not apply formatting at boundfield as datetime formatting can not be applied to strings .
If you do not wish to use ToShortDateString() just try above code without ToShortDateString() and use formatting at BoundField.