I am trying to display a gridview from a sql database using a query on a dropdownlist selected index changed for the dropdownlist.
Here is the code I currently have for this that I thought should work:
I am not getting any errors, the gridview just won't show up when i select a package from the dropdownlist.
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Clear();
DropDownList1.Items.Add(new ListItem("Select Package", "Select Package"));
DropDownList1.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct Package_Name from dbo.PackageDetail";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "Package_Name";
DropDownList1.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["datarepConnectionString"].ConnectionString;
SqlDataSource1.SelectCommand = "SELECT [ID], [PartNumber], [Qty], [PartDescription], [PR1], [PR2], [PR3], [EXTPR2], [EXTPR1], [EXTPR3] FROM [PackageDetail] where [Package_Name] = '" + DropDownList1.Text + "' ";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
ASP.NET:
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True" EnableViewState="true" >
</asp:DropDownList>
</center>
<p> </p>
<p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ID" ForeColor="Black" GridLines="Vertical" AllowSorting="True" Height="160px" Width="374px" EnableViewState="true" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="PartNumber" HeaderText="PartNumber" SortExpression="PartNumber" />
<asp:BoundField DataField="PartDescription" HeaderText="PartDescription" SortExpression="PartDescription" />
<asp:BoundField DataField="Qty" HeaderText="Qty" SortExpression="Qty" />
<asp:BoundField DataField="PR1" HeaderText="PR1" SortExpression="PR1" />
<asp:BoundField DataField="PR2" HeaderText="PR2" SortExpression="PR2" />
<asp:BoundField DataField="PR3" HeaderText="PR3" SortExpression="PR3" />
<asp:BoundField DataField="EXTPR2" HeaderText="EXTPR2" SortExpression="EXTPR2" />
<asp:BoundField DataField="EXTPR1" HeaderText="EXTPR1" SortExpression="EXTPR1" />
<asp:BoundField DataField="EXTPR3" HeaderText="EXTPR3" SortExpression="EXTPR3" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Help is very appreciated thank you.
Related
I have the following nested Girdview. The issue is when the parentgrid is loaded, it is showing 2 childgrids, one by the expand img, one below each row when I click on the expand img. The one by the expand img is unexpected and unwanted. Can someone help me fix this issue?
ASPX
<asp:GridView ID="gvLotDetails" runat="server" Width="600px" BackColor="White" AutoGenerateColumns="False" OnRowDataBound="gvLotDetails_DataBound" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="169px" DataKeyNames="ItemNumber">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="Images/plus.png" />
<asp:Panel ID="pnlLotDetailsExtend" runat="server">
<asp:GridView ID="gvLotDetailsExpand" runat="server" AutoGenerateColumns="false" DataKeyNames="Slab">
<Columns>
<asp:BoundField DataField="Slab" SortExpression="Slab" ReadOnly="True" HeaderText="Slab" />
<asp:BoundField DataField="Size" SortExpression="Size" ReadOnly="True" HeaderText="Size" />
<asp:BoundField DataField="Sqft" SortExpression="Sqft" ReadOnly="True" HeaderText="Sqft" />
<asp:BoundField DataField="Block" SortExpression="Block" ReadOnly="True" HeaderText="Block" />
<asp:BoundField DataField="Totalweight" SortExpression="Totalweight" ReadOnly="True" HeaderText="Totalweight" />
<asp:BoundField DataField="country" SortExpression="country" ReadOnly="True" HeaderText="Country" />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" HorizontalAlign="Right" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000" />
<AlternatingRowStyle BackColor="White" HorizontalAlign="Left" Font-Underline="true" />
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ItemNumber" SortExpression="ItemNumber"
ReadOnly="True" HeaderText="ItemNumber" />
<asp:BoundField DataField="whse" SortExpression="whse" ReadOnly="True"
HeaderText="Warehouse" />
<asp:BoundField DataField="Bundle" SortExpression="Bundle" ReadOnly="True"
HeaderText="Bundle" />
</Columns>
<PagerSettings Position="TopAndBottom" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" HorizontalAlign="Right" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000" />
<AlternatingRowStyle BackColor="White" HorizontalAlign="Left" Font-Underline="true" />
</asp:GridView>
JavaScript
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("[src*=plus]").live("click", function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "Images/minus.png");
});
$("[src*=minus]").live("click", function () {
$(this).attr("src", "Images/plus.png");
$(this).closest("tr").next().remove();
});
</script>
Code Behind
A button event triggers GetDeatils()
private void GetDetails()
{
query = "SELECT ItemNumber, WHSE, Bundle FROM labels_slab_details WHERE lot= '" + this.txtLot.Text.Trim() + "' and containernumber='" + this.ddlCont.SelectedValue +
"' GROUP BY ItemNumber, WHSE, Bundle ORDER BY Bundle, ItemNumber";
cn = new SqlConnection(cnBCStr);
SqlDataAdapter da = new SqlDataAdapter(query, cn);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
this.gvLotDetails.DataSource = ds.Tables[0];
this.gvLotDetails.DataBind();
this.gvLotDetails.Visible = true;
}
else
{
this.gvLotDetails.Visible = false;
this.errLabelDetail.Text = "* Create Bundle Data First! ";
return;
}
}
protected void gvLotDetails_DataBound(object Sender, GridViewRowEventArgs Ea)
{
if (Ea.Row.RowType == DataControlRowType.DataRow)
{
string ItemNumber = gvLotDetails.DataKeys[Ea.Row.RowIndex]["ItemNumber"].ToString();
GridView gvLotDetailsExpand = Ea.Row.FindControl("gvLotDetailsExpand") as GridView;
gvLotDetailsExpand.DataSource = GetData(string.Format("SELECT slab, size, sqft, block, totalweight, country FROM labels_slab_details WHERE LOT='" + this.txtLot.Text + "' AND ItemNumber='" + ItemNumber + "'"));
gvLotDetailsExpand.DataBind();
}
}
private static DataTable GetData(string query)
{
string cnBCStr = System.Configuration.ConfigurationManager.ConnectionStrings["conBarcodes_SQLWeb"].ConnectionString;
using (SqlConnection cn = new SqlConnection(cnBCStr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
cmd.Connection = cn;
da.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
}
}
I updated the code to remove some changes I made for testing the issue.
I found the answer. The extra childGrid can be hidden by updating the panel parameter.
<asp:Panel ID="pnlLotDetailsExtend" runat="server" Style="display: none">
I have problem in display gridview in my project asp.net .
This is my Gridview.
<asp:GridView ID="GridView1" runat="server" Width="100%" ViewStateMode="Enabled" AutoGenerateColumns="true" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" AutoGenerateSelectButton="true" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="#F7F7F7" />
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<SortedAscendingCellStyle BackColor="#F4F4FD" />
<SortedAscendingHeaderStyle BackColor="#5A4C9D" />
<SortedDescendingCellStyle BackColor="#D8D8F0" />
<SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>
This is my code in page load.
protected void Page_Load(object sender, EventArgs e)
{
try
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = connectionstring;
conn.Open();
string sql = "select * from merchant";
OracleCommand cmd = new OracleCommand(sql, conn);
OracleDataAdapter da = new OracleDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error : " + ex.ToString());
Label1.Text = ex.ToString();
}
}
why my Gridview can't display?. Someone please fix my problem.
Thanks
Change Your ASP.NET CODE
Exp:
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="ID" DataField="IDUser" ItemStyle-Width="50"/>
<asp:BoundField HeaderText="Name" DataField="Name" ItemStyle-Width="200"/>
<asp:BoundField HeaderText="Username" DataField="UserName" ItemStyle-Width="200"/>
</Columns>
</asp:GridView>
<asp:TextBox ID="searchDescription" runat="server" Height="26px" Width="270px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button2" runat="server" Text="Търси" onclick="Button2_Click" />
<br />
<br />
So here is my gridview :
<asp:GridView ID="GridView2" runat="server" HorizontalAlign="Center" AllowPaging="True"
AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Марка" HeaderText="Марка" SortExpression="Марка" />
<asp:BoundField DataField="Година" HeaderText="Година"
SortExpression="Година" />
<asp:BoundField DataField="Мощност" HeaderText="Мощност"
SortExpression="Мощност" />
<asp:BoundField DataField="Вносител" HeaderText="Вносител"
SortExpression="Вносител" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
I have a description text field and DropDownList and a button which generates a query that takes out from the DB * from the table where one of the column is equal to the selected Item from the DropDown and if in the description cell contains the subString from the description text field. So i want when the description cell appears into the gridView, the subString from the text field to be bolded.
Here is my button method:
protected void Button2_Click(object sender, EventArgs e)
{
string srchDescription = searchDescription.Text;
string slctItem = DropDownList1.SelectedItem.ToString();
con.Open();
SqlCommand cmdForDescription = new SqlCommand("SELECT Description FROM car_table WHERE Вносител = '" + slctItem + "'", con);
string descriptionText = cmdForDescription.ExecuteScalar().ToString();
bool containsDescription = descriptionText.Contains(srchDescription);
if (containsDescription)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM car_table WHERE Вносител = '" + slctItem + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView2.DataSource = ds;
GridView2.DataBind();
con.Close();
Label2.Visible = true;
}
}
First set htmlencode="false" on your bound field like this.
<asp:BoundField DataField="Description" HeaderText="Description"
htmlencode="false" SortExpression="Description" />
The in RowDataBound of your gridview write following.
if(e.Row.RowType == DataControlRowType.DataRow)
{
string textToReplace = searchDescription.Text;
string newText = "<b>" +searchDescription.Text + "</b>";
e.Row.Cells[4].Text =e.Row.Cells[4].Text.Replace(textToReplace, newText);
}
gridview has dropdowblist for approval, how to select specific record and save the data.
Gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" Font-Size="Smaller" Height="210px" Width="670px" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2" style="text-align: left">
<Columns>
<asp:BoundField DataField="class_id" HeaderText="Class_id" />
<asp:BoundField DataField="module_id" HeaderText="Module_id" />
<asp:BoundField DataField="lecturer_id" HeaderText="Lecturer" />
<asp:BoundField DataField="student_id" HeaderText="Student_id" />
<asp:BoundField DataField="submissionDate" HeaderText="Recieved" />
<asp:BoundField DataField="end_date" HeaderText="Submission_Date" />
<asp:BoundField DataField="ec_details" HeaderText="EC" />
<asp:TemplateField HeaderText = "Approval">
<ItemTemplate>
<asp:Label ID="lblApproval" runat="server" Text='<%# Eval("acceptance") %>' Visible = "false" />
<asp:DropDownList ID="ddAcceptance" runat="server" OnSelectedIndexChanged="ddAcceptance_SelectedIndexChanged">
<asp:ListItem>Approval</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
code behind
protected void btTOapprove_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
SqlCommand com = conn.CreateCommand();
conn.Open();
com.Parameters.Clear();
com.CommandText = "UPDATE [Marking] SET [acceptance]=#acc where [class_id]=#cid AND [module_id]=#mid AND [student_id]=#sid";
com.Parameters.Add("#acc", SqlDbType.VarChar).Value =
com.ExecuteNonQuery();
conn.Close();
}
when user select approval for example Yes or No, user must click save button to save data. How to select specific record and save its approval process.
You can simply make approval void for that :
void approval()
{
if (yes)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
SqlCommand com = conn.CreateCommand();
conn.Open();
com.Parameters.Clear();
com.CommandText = "UPDATE [Marking] SET [acceptance]=#acc where [class_id]=#cid AND [module_id]=#mid AND [student_id]=#sid";
com.Parameters.Add("#acc", SqlDbType.VarChar).Value =
com.ExecuteNonQuery();
conn.Close();
}
else
{
//Cancel the process
}
Then you can use the void :
protected void btTOapprove_Click(object sender, EventArgs e)
{
approval();
}
Update :
You can also make void for getting the value and send them to string.
void getvalue()
{
for (int i = 0; i < comboBox1.Items.Count; i++)
{
string str = comboBox1.Items[i].ToString(); ;
}
}
I cannot see where I'm doing wrong. No data is populated into the grid view.
HERE is my aspx gridview code
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="TeamMemberId"
Width="772px" CellPadding="4"
ForeColor="#333333" GridLines="Both" Height="16px"
onselectedindexchanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="TeamMemberLanId" HeaderText="LANID"
InsertVisible="False" ReadOnly="True" SortExpression="TeamMemberLanId" />
<asp:BoundField DataField="First Name" HeaderText="FirstName"
SortExpression="Name" />
<asp:BoundField DataField="Last Name" HeaderText="LastName"
SortExpression="Name" />
<asp:BoundField DataField="IsActive" HeaderText="Status" />
<asp:TemplateField HeaderText="Select">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelectAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333"
HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
and here is my code behind.
public void BindData()
{
try
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mystring"].ToString());
cmd.CommandText = "Select TeamMemberLanId, FirstName, LastName,IsActive from dbo.LoanOwnerStamp ORDER BY 2,3";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
else
{
//Bind Empty grdview with Columns names in Header and "No Team Member record found" message if no records are found in the database
BindEmptyGridWithHeader(GridView1, ds);
}
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');", true);
}
finally
{
con.Close();
}
}
Hope another pair of eyes can detect error in my gridview or code behind. BTW , da,ds, cmd, con are defined in the class.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
Query returns several rows,so there are no issues there.