Dropdownlist displaying two gridviews - c#

I currently have a drop down list that on selected index changed it displays data in a GridView based of the value of the drop down list. However, it is displaying the data in the existing GridView and then displaying another gridview next to the existing one with the exact information. I am just trying to display the data in the existing open.
C# Code:
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
DataTable table = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=
(local)\;Initial Catalog=SmallBatch;Integrated Security=True;"))
{
con.Open();
SqlDataAdapter DataAdapter = new SqlDataAdapter(string.Format("SELECT Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.Username = '" + DropDownList1.SelectedValue + "'"), con);
DataAdapter.Fill(table);
}
GridView1.DataSource = table;
GridView1.DataBind();
}
}
Existing Gridview:
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="Item ID" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemIDAdmin" Text='<%# Eval("ItemID")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="itemDescAdmin" Text='<%# Eval("ItemDesc")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bar Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="barQuantityAdmin" Text='<%# Eval("BarQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Storage Quantity" HeaderStyle-CssClass="gridview-header">
<ItemTemplate>
<asp:Label ID="storageQuantityAdmin" Text='<%# Eval("StorageQuantity")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Related

Insert data from gridview to database ,where row value in rows not equal to 0

I want to insert data into sql database from Gridview ,where rows values is not equal to 0 using asp.net C#
Below is my Html and C# code with DataTable and image is attached for more clearification I highlighted in red square where value is not equal to 0, will be inserted into the database.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText=" ID">
<ItemTemplate>
<asp:Label ID="I_ID" runat="server" Text='<%#Bind("I_ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Amount">
<ItemTemplate>
<asp:Label ID="I_Amt" runat="server" Text='<%#Bind("I_Amt")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Cheque_NO">
<ItemTemplate>
<asp:TextBox ID="C_NO" runat="server" ReadOnly="true" Text='<%#Bind("C_NO")%>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Cheque_Amount">
<ItemTemplate>
<asp:TextBox ID="C_Amt" runat="server" ReadOnly="true" Text='<%#Bind("C_Amt")%>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" >
<asp:ListItem Text="Pending" Value="1"></asp:ListItem>
<asp:ListItem Text="Received" Value="2"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C# Data
public partial class cheq : System.Web.UI.Page
{
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new System.Data.DataColumn[4] {
new System.Data.DataColumn("I_ID", typeof(int)),
new System.Data.DataColumn("I_Amt", typeof(int)),
new System.Data.DataColumn("C_NO", typeof(int)),
new System.Data.DataColumn("C_Amt", typeof(int)),
});
dt.Rows.Add(21, 339,500,2);
dt.Rows.Add(22, 622,400,25);
dt.Rows.Add(23, 226,474,23);
dt.Rows.Add(26, 339,0,0);
dt.Rows.Add(27, 339,0,0);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

Cell Text Always &nbsp:

I want to display the text of a specific cell in a textbox whenever I select a row from my gridview but whenever i do this "&nbsp" is the only text that I get even though the cell is not empty. Data on the gridview is bound from my database and I made a function where all the data from my database will be bound on my gridview. Below is the code that I'm using.
textbox1.Text = myGridView.SelectedRow.Cells[3].Text;
Markup
<asp:GridView ID="TraineeGrid" runat="server" AutoGenerateSelectButton ="true" AllowSorting="True" ShowHeader="true"
ShowFooter="false" AutoGenerateColumns="False" AutoGenerateEditButton="false" ScrollBars="Auto"
OnRowEditing="TraineeGrid_RowEditing"
OnRowUpdating="TraineeGrid_RowUpdating" OnRowCancelingEdit="TraineeGrid_RowCancelingEdit"
DataKeyNames="ID" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center"
EditRowStyle-VerticalAlign="Middle" OnInit="Page_Load" OnRowDataBound="TraineeGrid_RowDataBound" OnSelectedIndexChanging="TraineeGrid_SelectedIndexChanging" OnSelectedIndexChanged="TraineeGrid_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Delegate") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rank/Position">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbRankPos" runat="server" Text="Rank/Position" CommandName="Sort"
CommandArgument="RankPos" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newRankPos" TabIndex="2" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("RankPos") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRankPos" runat="server"
Text='<%# Eval("RankPos") %>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
Function that binds Data
private void PopulateData()
{
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
{
string path = "PopulateSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
using (SqlDataAdapter dataAdapt = new SqlDataAdapter(cmd))
{
dataAdapt.Fill(dataTable);
ViewState["NormalGrid"] = dataTable;
}
}
}
}
if (dataTable.Rows.Count > 0)
{
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
}
else
{
//Displays 'No Data Found' to gridview if there are no data in table
dataTable.Rows.Add(dataTable.NewRow());
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
TraineeGrid.Rows[0].Cells.Clear();
TraineeGrid.Rows[0].Cells.Add(new TableCell());
TraineeGrid.Rows[0].Cells[0].ColumnSpan = dataTable.Columns.Count;
TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
You can use this: textbox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
In OnSelectedIndexChanged :
protected void OnSelectedIndexChanged1(object sender, EventArgs e)
{
//Get the selected row
GridViewRow row = GridView1.SelectedRow;
if (row != null)
{
// With
// TextBox1.Text = (row.FindControl("lblLocalTime") as Label).Text;
// Without
TextBox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
}
}
Complete Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged1" AutoGenerateSelectButton="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
</Columns>
I've already found a solution. The problem is Im using TemplateField instead of BoundField that's why I cant use .Cells[] to get the specific cell that I wanted to get. However, if you are using TemplateField you can use .FindControl() and put in the ID of the label where your binding of data happens (ex. Text ='<%# Eval("FirstName") %>'). You can see that I put label on ItemTemplate to call it's ID.
Markup
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text = '<%# Eval("Delegate") %>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>' />
</EditItemTemplate>
</asp:TemplateField>
Code Behind
Label varName = (Label)rows.FindControl("lbName");
string name = varName.Text;

Unable to bind multiple dropdownlist in gridview on editing a row

I've two columns Customer Type and File Frequency in the gridview. When the grid is in normal mode I show the values using label. On editing the row, those two columns become dropdowns. I bind the dropdowns using OnRowDataBound="RowDataBound". But, Only first dropdown(whichever first written in the method) in the RowDataBound method getting bind on the edit mode.
.aspx
<asp:GridView ID="gvManageCustomers" DataKeyNames="Ship_To" runat="server" AutoGenerateColumns="False"
OnRowEditing="EditCustomer" OnRowDataBound="RowDataBound" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" CssClass="table table-bordered table-condensed">
<Columns>
<asp:TemplateField HeaderText="Customer Type">
<ItemTemplate>
<asp:Label ID="lblCustType" runat="server" Text='<%# Eval("Customer_Type")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCustType" runat="server" Text='<%# Eval("Customer_Type")%>' Visible="false">
</asp:Label>
<asp:DropDownList ID="ddlgvCustomerType" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Frequency">
<ItemTemplate>
<asp:Label ID="lblFileFreq" runat="server" Text='<%# Eval("FileFrequency")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblFileFreq" runat="server" Text='<%# Eval("FileFrequency")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlgvFileFreq" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
.cs
public DataTable FetchCustomerType()
{
string sql = "select distinct Customer_TypeID,Customer_Type from tbl_CustomerType";
SqlDataAdapter da = new SqlDataAdapter(sql, constr);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public DataTable FetchFileFrequency()
{
string sql = "SELECT distinct FileFrequency_ID,FileFrequency FROM [tbl_FileFrequency]";
SqlDataAdapter da = new SqlDataAdapter(sql, constr);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlgvFileFreq = (DropDownList)e.Row.FindControl("ddlgvFileFreq"); //getting binded
ddlgvFileFreq.DataSource = FetchFileFrequency();
ddlgvFileFreq.DataTextField = "FileFrequency";
ddlgvFileFreq.DataValueField = "FileFrequency_ID";
ddlgvFileFreq.DataBind();
ddlgvFileFreq.Items.FindByValue((e.Row.FindControl("lblFileFreq") as Label).Text).Selected = true;
DropDownList ddlgvCustomerType = (DropDownList)e.Row.FindControl("ddlgvCustomerType");
ddlgvCustomerType.DataSource = FetchCustomerType();
ddlgvCustomerType.DataTextField = "Customer_Type";
ddlgvCustomerType.DataValueField = "Customer_TypeID";
ddlgvCustomerType.DataBind();
ddlgvCustomerType.Items.FindByValue((e.Row.FindControl("lblCustType") as Label).Text).Selected = true;
}
}
}
catch (Exception ex)
{
//log error
errorlog.WriteErrorLog(ex.ToString());
}
}
The problem is in this line, it trows an exeption. That's why only the topmost binding would work.
ddlgvFileFreq.Items.FindByValue((e.Row.FindControl("lblFileFreq") as Label).Text).Selected = true;
But it looks like you want the DropDownList to have the correct SelectedValue. This is how you can do that.
DataRowView row = e.Row.DataItem as DataRowView;
DropDownList ddlgvFileFreq = (DropDownList)e.Row.FindControl("ddlgvFileFreq");
ddlgvFileFreq.DataSource = FetchFileFrequency();
ddlgvFileFreq.DataTextField = "FileFrequency";
ddlgvFileFreq.DataValueField = "FileFrequency_ID";
ddlgvFileFreq.DataBind();
try
{
ddlgvFileFreq.SelectedValue = row["FileFrequency_ID"].ToString();
}
catch
{
}
DropDownList ddlgvCustomerType = (DropDownList)e.Row.FindControl("ddlgvCustomerType");
ddlgvCustomerType.DataSource = FetchCustomerType();
ddlgvCustomerType.DataTextField = "Customer_Type";
ddlgvCustomerType.DataValueField = "Customer_TypeID";
ddlgvCustomerType.DataBind();
try
{
ddlgvCustomerType.SelectedValue = row["Customer_TypeID"].ToString();
}
catch
{
}
<asp:TemplateField HeaderText="Customer Type">
<ItemTemplate>
<asp:Label ID="lblCustType" runat="server" Text='<%# Eval("Customer_Type")%>'></asp:Label>
<asp:Label ID="lblCustTypeID" runat="server" Visible="false" Text='<%# (Eval("Customer_TypeID")) %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlgvCustomerType" runat="server" DataSource="<%# FetchCustomerType() %>" DataValueField="Customer_TypeID" DataTextField="Customer_Type" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Frequency">
<ItemTemplate>
<asp:Label ID="lblFileFreq" runat="server" Text='<%# Eval("FileFrequency")%>'></asp:Label>
<asp:Label ID="lblFileFreqID" runat="server" Visible="false" Text='<%# (Eval("FileFrequency_ID")) %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlgvFileFreq" runat="server" DataSource="<%# FetchFileFrequency() %>" DataValueField="FileFrequency_ID" DataTextField="FileFrequency" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
In onRowEditing Event
((DropDownList)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("ddlgvCustomerType")).SelectedValue = ((Label)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("lblCustTypeID")).Text;
((DropDownList)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("ddlgvFileFreq")).SelectedValue = ((Label)gvManageCustomers.Rows[e.NewEditIndex].Cells[0].FindControl("lblFileFreqID")).Text;

Save Grid View Textbox Data to database

I am trying to save grid view text box value and two other text box that are filled by user that are Total Marks and Marks Scored to data base am not sure how to pass back the values of that textboxs to data base on one click of submit
DB where the value to be saved are
Studentname RegNo TotalMarks Marksscored
asdsa 22 125 22
My Gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Names">
<ItemTemplate>
<asp:TextBox ID="txtStudent_Name" runat="server" Text='<%# Eval("StudentFirstName") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Register Number">
<ItemTemplate>
<asp:TextBox ID="txtreg_number" runat="server" Text='<%# Eval("StudentRegID") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Marks">
<ItemTemplate>
<asp:TextBox ID="txttotal_marks" runat="server" Text='' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Marks Scored">
<ItemTemplate>
<asp:TextBox ID="txtmarks_scored" runat="server" Text='' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
DataTable dt = new DataTable();
DataRow row = dt.NewRow();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox txtUsrId=(TextBox)GridView1.Rows[i].FindControl("Your textbox id");
string UserID = txtUsrId.Text;
string q="insert into details (name) values('"+UserID+"')";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}

Container.DisplayIndex not working with paging in ASP.NET

I have a gridview that is bound with data from code behind. Paging is applied in gridview. Everything works fine. For showing Row-Index i use Container.DisplayIndex.
When i go to next page through paging, every time gridview bind perfectly but DisplayIndex start with 1 to pagesize. I don't know what is wrong with the code.
Here is Asp.NET Code:
<asp:GridView runat="server" ID="dlAddress" AutoGenerateColumns="false" AllowPaging="True" OnPageIndexChanging="dlAddress_PageIndexChanging" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblRowNumber" Text='<%# Container.DisplayIndex + 1 %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle HorizontalAlign="Center"/>
</asp:GridView>
C# Code:
public void bindGridView()
{
DBACon.Open();
SqlCommand Cmd = new SqlCommand("getAddresses", DBACon);
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter AHadp = new SqlDataAdapter(Cmd);
AHadp.Fill(DS);
dlAddress.DataSource = DS;
dlAddress.DataBind();
}
protected void dlAddress_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dlAddress.PageIndex = e.NewPageIndex;
bindGridView();
}
Here,
ASPX:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5" AutoGenerateColumns="False" DataKeyNames="AddressID" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText="RowNumber">
<ItemTemplate>
<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Categories