Passing of data from gridview to a new page - c#

It is something very simple but i am stuck on this for ages.
So i had created a datatable and got the data onto a gridview. Great
Made the Sheet_id clickable and when clicking it i will direct to a new page.
However i want to get the sheet_id which i selected from the gridview in order to use it for other sql query.
How do i pass that sheet_id from one page to another page using the linkbutton.
This is ExistingSheet.aspx
<asp:GridView ID="grdSheet" runat="server" AutoGenerateColumns="False"
CssClass="tablesorter table table-bordered table-hover table-striped tblCtr"
>
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="hdnSheetId" runat="server" Text='<%# Eval("SNO")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sheet ID">
<ItemTemplate>
<asp:LinkButton runat="server" ID="sheetId" CommandName="sheet_id" CommandArgument='<%# Eval( "sheet_id")%>' Text='<%# Eval( "sheet_id")%>' OnClick="" PostBackUrl="~/SheetDetail.aspx">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
This is ExistingSheet.aspx.cs
protected void grdSheet_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Redirect("SheetDetail.aspx" + e.CommandArgument);
}
This is the page i wanted to get the data to SheetDetail.aspx.cs
public void FillGridSheet()
{
eExistingSheetQuery existingSheetQuery = new eExistingSheetQuery();
grdSheetDetail.DataSource = existingSheetQuery.DisplayReportSheet(**SHEET ID TO BE PLACED HERE**);
grdSheetDetail.DataBind();
}
This is eExistingSheetQuery.cs
public DataTable DisplayReportSheet(string sheetId)
{
try
{
conn = new SqlConnection(estocktake);
conn.Open();
DataTable dtd = new DataTable();
GridView gvd = new GridView();
cmds = new SqlCommand("Select ROW_NUMBER( ) OVER (order by sheet_id) as SNO, csd.Barcode, csd.ItemId, pm.Description, csd.Quantity " +
"from CountSheetDetails csd " +
"join ProductMaster pm on pm.Barcode = csd.Barcode and pm.ItemId = csd.ItemId " +
"where csd.SheetId = '" + sheetId + "' and pm.Status ='A';",conn);
adpt = new SqlDataAdapter();
adpt.SelectCommand = cmds;
cmds.ExecuteNonQuery();
adpt.Fill(dtd);
conn.Close();
conn.Dispose();
for (int i = 0; i < dtd.Rows.Count; i++)
{
dtd.Rows[i]["SNO"] = i + 1;
}
return dtd;
}
catch (Exception)
{
conn.Close();
conn.Dispose();
return null;
}
}
i wanted to use the id to beable to use it for the next query that i am going to pull from SQL
I had seen a few example but i do not think i really understand. Any suggestion will be great. thanks!

I think what you're asking is a way to pass data from one GridView to another, but on a different page?
Using a loop mechanism, I suggest you loop through your source Gridview and copy them into your destination GridView. Get this to work first on a single page first - ie GridView to GridView.
For example, you'll need a trigger. Here's a Button trigger to get the data ...
GridView1 = your source GridView
GridView2 = your destination GridView
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("ColumnName1"));
dt.Columns.Add(new DataColumn("ColumnName2"));
dt.Columns.Add(new DataColumn("ColumnName3"));
foreach (GridViewRow gvr in GridView1.Rows)
{
if (((CheckBox)gvr.Cells[4].FindControl("CheckBox")).Checked == true)
{
dr = dt.NewRow();
dr["ColumnName1"] = ((Label)gvr.Cells[0].FindControl("Label")).Text;
dr["ColumnName2"] = ((Label)gvr.Cells[1].FindControl("Label")).Text;
dr["ColumnName3"] = ((Label)gvr.Cells[2].FindControl("Label")).Text;
dt.Rows.Add(dr);
}
}
foreach (GridViewRow gvr in GridView2.Rows)
{
dr = dt.NewRow();
dr["ColumnName1"] = ((Label)gvr.Cells[0].FindControl("Label")).Text;
dr["ColumnName2"] = ((Label)gvr.Cells[1].FindControl("Label")).Text;
dr["ColumnName3"] = ((Label)gvr.Cells[2].FindControl("Label")).Text;
dt.Rows.Add(dr);
}
GridView2.DataSource = dt;
GridView2.DataBind();
}
Once you get this to work, your way, then we figure out how to pass the data across different web URLs.
One approach is to use SessionState[]. Here.
The concept is basically about passing data into memory, which is the SessionState or ViewState, and then retrieving that data from the receiving page via it's PageLoad() event. OR you save the data into a temporary table, and reload it again onto the new page, using standard DataSource attributes.
Examples here and here.

Related

Can't get the grid view data and store it to database

<div class="container">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Size="Medium">
<asp:TemplateField HeaderText="Student ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Width="80px" Text='<%#Eval("studentID") %>'/>
</ItemTemplate>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton runat="server" OnCommand="LinkButton_Click" Text=" VoteCandidate"> </asp:LinkButton>
</ItemTemplate>
</asp:GridView>
<div>
<asp:Label ID="Label1" runat="server" ></asp:Label>
</div>
</div>
Here is my form to show the gridview.
protected void loadCandidate()
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select studentID from candidate where faculty='FOCS'", con);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
protected void LinkButton_Click(Object sender, EventArgs e)
{
String MyConnection2 = "Server=localhost;database=ovs;Uid=root;password=; Convert Zero Datetime=True";
foreach (GridViewRow g1 in GridView1.Rows)
{
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
String query = "insert into voting (studentID)values ('" + g1.Cells[0].Text + "')" ;
MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MyConn2.Close();
}
}
When I execute the sql insert command, no error occur, but I expect the studentID that displayed in the gridview being stored in the voting table, but the studentID on the voting table are empty.
Since you use a template field in your GridView, you can't use the cell directly, you need to look for the label inside the cell like this:
foreach (GridViewRow g1 in GridView1.Rows)
{
Label lblStudentId = (Label)g1.Cells[0].FindControl("lblID");
string studentId = lblStudentId.Text;
// now proceed with your inserting.
}
But if you using the loop the way you do it right now, there will be an insert for every row in the GridView, not only for the one you clicked on...
If you want to get the Id for the row the LinkButton is in, don't iterate over the rows. Instead use the NamingContainer-property of the sender like this:
LinkButton linkButton = (LinkButton)sender;
GridViewRow g1 = (GridViewRow)linkButton.NamingContainer;
Label lblStudentId = (Label)g1.Cells[0].FindControl("lblID");
string studentId = lblStudentId.Text;
// now proceed with your inserting.
For more details look at this question and answer

how to rearrange column in gridview?

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>

Display DropDownlist when click on specific cell asp.net table

I am trying to figure it out how can I display a dropDownList on a specific cell in the table right after clicking a button "Show DropDownlist" located on that cell.
This is the behind code , right now it is displaying the dropDownList at the last cell of each row. and I want to make it appear only when a button is clicked.
while (rdr.Read())
{
TableRow tRow = new TableRow();
myTable.Rows.Add(tRow);
for (int i = 0; i <= 4; i++)
{
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
if (i == 4)
{
tCell.Controls.Add(SM_List()); //Adding the dropdownlist
tRow.Cells.Add(tCell);
continue;
}
tCell.Text = rdr.GetString(i);
tCell.Attributes.Add("onmouseover", "this.style.cursor = 'pointer'; this.style.backgroundImage = ''; ");
tCell.Attributes.Add("onClick", "getData()");
tRow.Cells.Add(tCell);
}
/* iterate once per row */
}
I want to add this code, so it will be a button at first , instead of a drop down list :
Button bt = new Button();
bt.Text = "Switch";
bt.Click += new EventHandler(DropDownList_Show);
tCell.Controls.Add(bt);
But I am not sure how to display the DropDownList at the exact cell the button was located. and also I want to do some actions when Value was selected in the dropdownlist.
Can you please assist , I feel a little bit lost.
You can solve this issue easily by using GridView in ASP.NET.
Let say the GridView is declared as following in ASPX page.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" />
<asp:BoundField DataField="Token" />
<asp:BoundField DataField="Secret" />
<asp:ButtonField CommandName="ShowDropDown" Text="Show" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropDownList" runat="server" Visible="false">
<asp:ListItem Text="Valid" Value ="1"></asp:ListItem>
<asp:ListItem Text="Invalie" Value ="2"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Following is the method in code behind which populates the GridView.
private void BindGridView()
{
var tokens = new List<AccessToken>();
using (var conn = new SqlConnection("Server=somedbserver;Database=somedatabase;User Id=someuser;Password=somepassword;"))
{
using (var command = new SqlCommand())
{
command.Connection = conn;
command.CommandText = "SELECT Id, Token, Secret FROM Tokens";
command.CommandType = System.Data.CommandType.Text;
conn.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var token = new AccessToken();
token.Id = reader.GetInt32(0);
token.Token = reader.GetString(1);
token.Secret = reader.GetString(2);
tokens.Add(token);
}
}
}
}
GridView1.DataSource = tokens;
GridView1.DataBind();
}
And I am calling this method in Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridView();
}
}
Following is the event handler of RowCommand event of GridView which will display the dropdown list in the column next to the button which is clicked.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "ShowDropDown")
{
var row = GridView1.Rows[Convert.ToInt32(e.CommandArgument)];
//Using Cell[4] coz the Dropdownlist is in 5th column of the row.
//You need to replace 4 with appropriate column index here.
//Also replace "dropDownList" with the ID assigned to the dropdown list in ASPX.
var ddl = (DropDownList)row.Cells[4].FindControl("dropDownList");
if(ddl != null)
{
ddl.Visible = true;
}
}
}
You will able resolve your issue if you follow this approach.

c# Select all checkbox with datagridview using dataset

This is a basic question but i didn't find appropriate answers : I have a dataset that is shown in dataGridview and it contains a column Is_Alarm of type bit (boolean) , i want to insert a Select all checkbox in that column.
I have seen many solutions but they are all about inserting a new checkbox in datagridView .
What i want is insert it after columns are shown , here's my code :
SqlDataAdapter adap= new SqlDataAdapter(select_query,con);
ds = new DataSet();
adap.Fill(ds, "Event_test");
dataGridView1.DataSource = ds.Tables[0];
I had same issue what I did might be useful for you
This is code used for gridview
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Next I Loaded data( MyTable field had id,username,email etc)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlDataAdapter adap = new SqlDataAdapter("Select * From UserInfo", con);
DataSet ds = new DataSet();
adap.Fill(ds);
con.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}
For getting Ids of selected records I used few lines which is described here
http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx and modified in this way
protected void btnCheckSelected_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
if (chkRow.Checked)
{
string ids = row.Cells[1].Text;
ListBox1.Items.Add(ids);
}
}
}
}

add new row in gridview after binding C#, ASP.net

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();

Categories

Resources