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>
Related
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();
}
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.
I am using this example to sort GridView loaded from DataTable. I also reviewed this post - I used sajanyamaha advice by adding columns to DataTable and that's when GridView's date columns starting sorting properly with one peculiarity. I have 11 columns, first column is a selectcommand that redirects to another page. I have no boundfields or template fields, gridview is filled from datatable in code behind.
The problem is sorting and paging work fine on all columns EXCEPT the 2 Date columns. The Date columns, ReviewDue and SubmittedDate. They sort correctly but they do not retain the sort order while paging. GridView will reset to page 1 at each sort column change which causes the user to never see past page 1 when Date column is sorted. The issue I am trying to resolve and understand is why do all the other columns function correctly but the Date columns behave differently? What custom handling is needed to get date columns to behave like the other string or int columns?
I have googled plenty but I don't find anything with this oddity.
Here is my pertinent code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["SortExpr"] = "EPRID";
ViewState["SortDir"] = " DESC";
if (blnIsAdmin == true || blnIsManager == true)
{
BindData();
}
else
{
//redirect
Response.Redirect("~/ErrorPages/AccessDenied.aspx");
}
}
}
private void BindData()
{
GridView1.DataSource = this.GetData();
GridView1.DataBind();
}
private DataTable GetData()
{
string cmdStr = "SELECT * FROM ….ORDER BY " + ViewState["SortExpr"].ToString() + " " + ViewState["SortDir"].ToString();
DataTable table = new DataTable();
table.Columns.Add("EPRID", typeof(Int32));
table.Columns.Add("FormName", typeof(String));
table.Columns.Add("Name", typeof(String));
table.Columns.Add("Completed", typeof(Boolean));
table.Columns.Add("Sup1", typeof(String));
table.Columns.Add("Sup2", typeof(String));
table.Columns.Add("Sup3", typeof(String));
table.Columns.Add("ReviewDue", typeof(DateTime));
table.Columns.Add("SubmittedDate", typeof(DateTime));
table.Columns.Add("SubmittedBy", typeof(String));
table.Columns.Add("DocID", typeof(Int32));
using (SqlConnection conn = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
cmd.CommandType = CommandType.Text;
//get all EPRs (unfiltered grid)
if (blnIsAdmin == true ")
{
cmdStr = "SELECT * FROM … ORDER BY " + ViewState["SortExpr"].ToString() + " " + ViewState["SortDir"].ToString();
using (SqlDataAdapter da = new SqlDataAdapter(cmdStr, conn))
{
da.Fill(table);
}
}
else if (blnIsManager == true)
{
cmdStr = "SELECT * FROM… WHERE user = #user …ORDER BY " + ViewState["SortExpr"].ToString() + " " + ViewState["SortDir"].ToString();
using (SqlDataAdapter da = new SqlDataAdapter(cmdStr, conn))
{
da.SelectCommand.Parameters.Add(new SqlParameter { ParameterName = "#user", Value = strCurrentUser, SqlDbType = SqlDbType.VarChar, Size = 50 });
da.Fill(table);
}
}
}
}
return table;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//go to page 1 when sorting
GridView1.PageIndex = 0;
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
ViewState["SortDir"] = " DESC";
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
ViewState["SortDir"] = " ASC";
}
ViewState["SortExpr"] = sortExpression;
}
private void SortGridView(string sortExpression, string direction)
{
ViewState["SortExpr"] = sortExpression;
ViewState["SortDir"] = direction;
//get unfiltered grid
DataTable dt = GetData();
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
//ViewState["sortDirection"] = SortDirection.Ascending;
ViewState["sortDirection"] = SortDirection.Descending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
<asp:GridView ID="GridView1" runat="server"
onselectedindexchanged="GridView1_SelectedIndexChanged"
AllowPaging="True"
AllowSorting="True"
Caption="List of awaiting or completed employee performance reviews"
PageSize="25"
onsorting="GridView1_Sorting"
onpageindexchanging="GridView1_PageIndexChanging"
CellPadding="4"
DataKeyNames="EPRID,DocID"
ForeColor="#333333" GridLines="None"
onrowcommand="GridView1_RowCommand"
onrowdatabound="GridView1_RowDataBound"
onselectedindexchanging="GridView1_SelectedIndexChanging"
CssClass="GridStyle" >
<RowStyle BackColor="#F7F6F3" ForeColor="Black" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
</Columns>
<FooterStyle Font-Bold="True" ForeColor="Black" />
<PagerStyle ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="Black" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
Solved! Part of the issue was with the SELECT statement in the view that was used in Sql query strings' FROM clause, cmdStr (details of this were left out of my original question for brevity-possibly my first error in getting proper help?). In the views' SELECT statement, the 2 datetime columns were constructed like this:
,Convert(varchar(10),NextReview,112) as ReviewDue
,Convert(varchar(10),SubmittedDate,112) as SubmittedDate
and should have been simply:
,NextReview as ReviewDue
,SubmittedDate
,etc...
(BTW it made no differnce which standard I used, 101, 110, 111, 112...). Also the corresponding data types in the DataTable's Add() method should match as DateTimein GetData(). Finally I added a condition and modified the ORDER BY clause in the SQL inline query, cmdStr to:
//pass ViewState to variable for use in cmdStr when DateTime columns are sorted on
strExpression = ViewState["SortExpr"].ToString();
if (strExpression == "ReviewDue" || strExpression == "SubmittedDate")
{
cmdStr = "SELECT * FROM vwView ORDER BY CONVERT(DATE, " + strExpression + ", 120) " + ViewState["SortDir"].ToString();
}
else
{
//use original cmdStr
}
In the gridviews _RowDataBound() event I also formated the date to show Date part only in the grid like this:
//ReviewDue will never be null
e.Row.Cells[8].Text = Convert.ToDateTime(((DataRowView)e.Row.DataItem)["ReviewDue"]).ToString("d");
//SubmittedDate can be null, handle null
object dtmDate9 = ((DataRowView)e.Row.DataItem)["SubmittedDate"];
if (dtmDate9 == DBNull.Value)
{
e.Row.Cells[9].Text = String.Empty;
}
else
{
e.Row.Cells[9].Text = Convert.ToDateTime(((DataRowView)e.Row.DataItem)["SubmittedDate"]).ToString("d");
}
I am using asp DropDownList inside RadGrid, and trying to Add and Update the DropDownList item inside Database table.
Below is the HTML code for DropDownList inside RadGrid's EditItemTemplate:
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>'></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
C# Code:
public DataTable GetAccCode(string CompanyCode)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("[Invoice].[usp_tbl_AccountCode_DL_Test]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyCode", CompanyCode);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
return dt;
}
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField = "AccountDescription";
ddl.DataValueField = "AccountCodeID";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
//Select particular dropdown value while "Edit"
string accCodeID = item.GetDataKeyValue("AccountCodeID").ToString();
Label lblAcCode2 = item.FindControl("lblAcCode") as Label;
//if (!string.IsNullOrEmpty(lblAcCode2.Text))
//{
ddl.SelectedValue = lblAcCode2.Text;
//}
//string SelectedVal = ddl.SelectedValue;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [AccountCode]+' - '+[AccountDescription] as [AccountDescription] FROM [Sunway_AP].[Invoice].[tbl_AccountCodeTest] where AccountCodeID='" + accCodeID + "' ", con);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
finally
{
con.Close();
}
ddl.SelectedValue = dt.ToString();
string SelectedVal = ddl.SelectedValue;
}
}
}
This is the Stored Procedure:
ALTER PROCEDURE [Invoice].[usp_tbl_AccountCode_DL_Test]
#CompanyCode nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT [AccountCodeID] ,[AccountCode]+' - '+[AccountDescription] as [AccountDescription]
FROM [Sunway_AP].[General].[tbl_AccountCode] (NOLOCK)
Where [CompanyCode] = #CompanyCode
order by [AccountCode]+' - '+[AccountDescription]
END
My problem is: I am unable to fetch the "DropDownList's" selected value for a particular Id (particular row of RadGrid), while Edit.
Everytime when I try to set the Selected Value of DropdownList from code behind, it shows me 1st item '- Select -' inside the selected value.
Please reply what is wrong in my code.
I am very new in Telerik. Thanks in advance.
Modified my posted code as below:
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField="*your text field*";
ddl.DataValueField="*your Value field*";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
Label lblAcCode2 = item.FindControl("lblAcCode2") as Label;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
ddl.SelectedItem.Text = lblAcCode2.Text;
ddl.SelectedValue = lblAcCode2.Text;
}
}
}
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
Hope this helps...
All the best...
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();