I need shows the file names from a folder into a GridView control.
I thinked use the Directory class.
In my database I have the column sFolder with this value for each row:
control/Imp/foo
I have tried this tutorial on the web but I can't get the file names from a folder into a GridView control.
I don't have error but the GridView is empty even if the path to the folder is correct.
My code below.
Can you help me?
Thank you in advance for any help, really appreciated
.cs
dt2 = new DataTable();
ds2 = new DataSet();
sql = #String.Format(" SELECT * FROM tbl_2 WHERE sFolder IN ('control/Imp/foo'); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
using (OdbcCommand cmd =
new OdbcCommand(sql, cn))
{
OdbcDataAdapter adapter =
new OdbcDataAdapter(cmd);
adapter.Fill(ds2);
if (ds2.Tables.Count > 0)
{
dt2 = ds2.Tables[0];
FilePath = Server.MapPath("/myFolder/" + ds2.Tables[0].Rows[0]["sFolder"].ToString().Replace('/', '\\'));
Response.Write(FilePath);
// the response write FilePath is C:\inetpub\wwwroot\aspnet\myFolder\control\Imp\foo //
string[] filesLoc = Directory.GetFiles(FilePath);
List<ListItem> files = new List<ListItem>();
foreach (string file in filesLoc)
{
files.Add(new ListItem(Path.GetFileName(file)));
}
gvDownload.DataSource = files;
gvDownload.DataBind();
}
}
}
return ds2;
.aspx
<asp:GridView ID="gvDownload" EmptyDataText="Data empty"
runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" GridLines="Vertical">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="Text" HeaderText="FileName" />
</Columns>
</asp:GridView>
#Edit 01
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
RetrieveProductsDowload();
}
private DataSet RetrieveProductsDowload()
{
dt2 = new DataTable();
ds2 = new DataSet();
sql = #String.Format(" SELECT * FROM tbl_2 WHERE sFolder IN ('control/Imp/foo'); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
using (OdbcCommand cmd =
new OdbcCommand(sql, cn))
{
OdbcDataAdapter adapter =
new OdbcDataAdapter(cmd);
adapter.Fill(ds2);
if (ds2.Tables.Count > 0)
{
dt2 = ds2.Tables[0];
FilePath = Server.MapPath("/myFolder/" + ds2.Tables[0].Rows[0]["sFolder"].ToString().Replace('/', '\\'));
Response.Write(FilePath);
// the response write FilePath is C:\inetpub\wwwroot\aspnet\myFolder\control\Imp\foo //
string[] filesLoc = Directory.GetFiles(FilePath);
List<ListItem> files = new List<ListItem>();
foreach (string file in filesLoc)
{
files.Add(new ListItem(Path.GetFileName(file)));
}
gvDownload.DataSource = files;
gvDownload.DataBind();
}
}
}
return ds2;
}
Please, try this:
string[] allfiles = Directory.GetFiles(FilePath, "*", SearchOption.AllDirectories);
gvDownload.DataSource = allfiles;
gvDownload.DataBind();
Related
this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.
I'm trying to build a simple page that will allow for bulk SQL Searches using a text area. The textbox is split on each new line and each line taken as a parameter to query. The resulting row is then added to a DataTable.
There isn't a problem with the query and the DataTable is built and returned as I expected when checked through debug mode. The only problem is when I attempt to bind the DataTable to the gridview , the gridview is left without rows.
I have been scratching my head at this for a hwile now and cannot figure out why the DataTable will not bind. The column names all match up but the actual table in result is unnamed. Is this an issue?
Here's the code.
ASPX:
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="SIM NUMBER" HeaderText="SIM NUMBER" />
<asp:BoundField DataField="Voice" HeaderText="Voice" />
<asp:BoundField DataField="IMSI" HeaderText="IMSI" />
<asp:BoundField DataField="Tariff" HeaderText="Tariff" />
<asp:BoundField DataField="Contract Start" HeaderText="Contract Start" />
<asp:BoundField DataField="Supplier" HeaderText="Supplier" />
</Columns>
</asp:GridView>
And the C# Code:
public partial class Query : System.Web.UI.Page
{
protected static string numbers = "";
protected static string number;
protected static DataTable result = new DataTable();
protected static string simNumber;
protected static string voice;
protected static string IMSI;
protected static string tariff;
protected static string contractStart;
protected static string supplier;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
result.Reset();
result.Columns.Add("SIM NUMBER", typeof(string));
result.Columns.Add("Voice", typeof(string));
result.Columns.Add("IMSI", typeof(string));
result.Columns.Add("Tariff", typeof(string));
result.Columns.Add("Contract Start", typeof(string));
result.Columns.Add("Supplier", typeof(string));
numbers = TextArea1.Value.ToString();
search();
GridView1.DataSource = result;
GridView1.DataBind();
}
protected static void search()
{
string[] split = numbers.Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (string line in split)
{
if (line == string.Empty)
continue;
number = line;
getSupplierInfo();
}
}
protected static void getSupplierInfo()
{
DataTable DT = new DataTable();
using (SqlConnection conn = new SqlConnection(connections.supplierInfo()))
{
string sql = " SELECT * FROM UnionSuppliers WHERE SIM_NUMBER LIKE #parameter ";
conn.Open();
using (SqlCommand select = new SqlCommand
{
CommandType = CommandType.Text,
CommandTimeout = 300,
CommandText = sql,
Connection = conn
})
{
select.Parameters.AddWithValue("#parameter", number);
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter.SelectCommand = select;
adapter.Fill(ds);
DT = ds.Tables[0];
}
}
foreach (DataRow dr in DT.Rows)
{
simNumber = dr["SIM_NUMBER"].ToString();
voice = dr["Voice"].ToString();
IMSI = dr["IMSI"].ToString();
tariff = dr["Tariff"].ToString();
contractStart = dr["Contract_start"].ToString();
supplier = dr["Supplier"].ToString();
addRow();
}
}
protected static void addRow()
{
DataRow simResult = result.NewRow();
simResult["SIM Number"] = simNumber;
simResult["Voice"] = voice;
simResult["IMSI"] = IMSI;
simResult["Tariff"] = tariff;
simResult["Contract Start"] = contractStart;
simResult["Supplier"] = supplier;
result.Rows.Add(simResult);
}
}
Any help would be very much appreciated. I'm sure its something really simple that i'm missing.
Thanks
Try changing:
AutoGenerateColumns="false"
to:
AutoGenerateColumns="true"
I Think you can try like this in aspx file
<Columns>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Your_Field_Name") %>'></asp:Label>
</ItemTemplate>
</Columns>
and in cs file just fit below code
DataTable DT = new DataTable();
using (SqlConnection conn = new SqlConnection(connections.supplierInfo()))
{
string sql = " SELECT * FROM UnionSuppliers WHERE SIM_NUMBER LIKE #parameter ";
conn.Open();
using (SqlCommand select = new SqlCommand
{
CommandType = CommandType.Text,
CommandTimeout = 300,
CommandText = sql,
Connection = conn
})
{
select.Parameters.AddWithValue("#parameter", number);
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter.SelectCommand = select;
adapter.Fill(ds);
DT = ds.Tables[0];
}
}
And now bind your Datatable to Grid View.
GridView1.DataSource = DT;
GridView1.DataBind();
Please help me to keep checkbox is checked after checking checkbox for updating corresponding row in Gridview.this my complete source code.Please help Me to keep checkbox inside Gridview checked after update button click.I met scenario that in order to identify which user's data going to be update so.Please help me friends.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" onpageindexchanging=" grvDetails_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Page">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="radID" runat="server" onclick ="CheckSingleCheckbox(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="FirstName" HeaderText="FirstName"/>
<asp:BoundField DataField="LastName" HeaderText="LastName"/>
<asp:BoundField DataField="Gender" HeaderText="Gender"/>
<asp:BoundField DataField="Email" HeaderText="Email"/>
<asp:BoundField DataField="Phone" HeaderText="Phone"/>
<asp:BoundField DataField="ContactAddres" HeaderText="ContactAddres"/>
<asp:BoundField DataField="State" HeaderText="ContactState"/>
<asp:BoundField DataField="Country" HeaderText="ContactCountry"/>
<asp:BoundField DataField="CommunicationAddress" HeaderText="CommunicationAddress"/>
<asp:BoundField DataField="State1" HeaderText="CommunicationState"/>
<asp:BoundField DataField="Country1" HeaderText="CommunicationCountry"/>
<asp:BoundField DataField="statec" HeaderText="ContactCountry" ShowHeader="false" />
<asp:BoundField DataField="countryc" HeaderText="CommunicationAddress" ShowHeader="false" />
<asp:BoundField DataField="CommunicationState" HeaderText="CommunicationState" ShowHeader="false" />
<asp:BoundField DataField="CommunicationCountry" HeaderText="CommunicationCountry" ShowHeader="false" />
</Columns>
</asp:GridView>
And this is my c# page and I'm posting code for update
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Collections;
namespace Reg
{
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridView();
populate1();
populate2();
}
}
public void populate1()
{
DataSet ds = new DataSet();
SqlConnection con;
SqlCommand cmd = new SqlCommand();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand com = new SqlCommand("select *from CountryDetail", con);
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
ddlCountryPermanent.DataTextField = ds.Tables[0].Columns["Country"].ToString();
ddlCountryPermanent.DataValueField = ds.Tables[0].Columns["CID"].ToString();
ddlCountryPermanent.DataSource = ds.Tables[0];
ddlCountryPermanent.DataBind();
ddlCountryPermanent.Items.Insert(0, "Select");
ddlCountryCommunication.DataTextField = ds.Tables[0].Columns["Country"].ToString();
ddlCountryCommunication.DataValueField = ds.Tables[0].Columns["CID"].ToString();
ddlCountryCommunication.DataSource = ds.Tables[0];
ddlCountryCommunication.DataBind();
ddlCountryCommunication.Items.Insert(0, "Select");
}
public void populate2()
{
DataSet ds = new DataSet();
SqlConnection con;
SqlCommand cmd = new SqlCommand();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand com = new SqlCommand("select *from StatesDetail", con);
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
ddlStatePermanent.DataTextField = ds.Tables[0].Columns["State"].ToString();
ddlStatePermanent.DataValueField = ds.Tables[0].Columns["SID"].ToString();
ddlStatePermanent.DataSource = ds.Tables[0];
ddlStatePermanent.DataBind();
ddlStatePermanent.Items.Insert(0, "Select");
ddlStateCommunication.DataTextField = ds.Tables[0].Columns["State"].ToString();
ddlStateCommunication.DataValueField = ds.Tables[0].Columns["SID"].ToString();
ddlStateCommunication.DataSource = ds.Tables[0];
ddlStateCommunication.DataBind();
ddlStateCommunication.Items.Insert(0, "Select");
}
protected void saveButton_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection con;
SqlCommand cmd = new SqlCommand();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
cmd = new SqlCommand("proc_Registers", con);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
if (RdoGender.SelectedItem.Value == "0")
{
cmd.Parameters.AddWithValue("#Gender", "0");
}
else
{
cmd.Parameters.AddWithValue("#Gender", "1");
}
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("#ContactAddres", txtAddressCon.Text);
var statcon = ddlStatePermanent.SelectedItem.Value;
cmd.Parameters.AddWithValue("#ContactState", statcon);
var ddlCourtyCon = ddlCountryPermanent.SelectedItem.Value;
cmd.Parameters.AddWithValue("#ContactCountry", ddlCourtyCon);
cmd.Parameters.AddWithValue("#CommunicationAddress", txtAddressPer.Text);
var statper = ddlStateCommunication.SelectedItem.Value;
cmd.Parameters.AddWithValue("#CommunicationState", statper);
var ddlCourtyPer = ddlCountryCommunication.SelectedItem.Value;
cmd.Parameters.AddWithValue("#CommunicationCountry", ddlCourtyPer);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
gridView();
}
public void gridView()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("proc_FinalDataGridviewNew", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.PageSize = 5;
GridView1.Columns[1].Visible = true;
GridView1.Columns[13].Visible = true;
GridView1.Columns[14].Visible = true;
GridView1.Columns[15].Visible = true;
GridView1.Columns[16].Visible = true;
Page.DataBind();
GridView1.Columns[1].Visible = false;
GridView1.Columns[13].Visible = false;
GridView1.Columns[14].Visible = false;
GridView1.Columns[15].Visible = false;
GridView1.Columns[16].Visible = false;
}
protected void grvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
DataBind();
gridView();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[13].Visible = false;
e.Row.Cells[14].Visible = false;
e.Row.Cells[15].Visible = false;
e.Row.Cells[16].Visible = false;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("radID") as CheckBox;
if (chk.Checked)
{
var ID = row.Cells[1].Text;
var fname = row.Cells[2].Text;
var lname = row.Cells[3].Text;
var gendr = row.Cells[4].Text;
var mail = row.Cells[5].Text;
var phne = row.Cells[6].Text;
var addrscon = row.Cells[7].Text;
var statecon = row.Cells[13].Text;
var countrycon = row.Cells[14].Text;
var addrsper = row.Cells[10].Text;
var stateper = row.Cells[15].Text;
var countryper = row.Cells[16].Text;
txtID.Text = ID;
txtFirstName.Text = fname;
txtLastName.Text = lname;
string gndr;
if (gendr == "Male")
{
gndr = "0";
}
else
{
gndr = "1";
}
RdoGender.SelectedValue = gndr;
txtEmail.Text = mail;
txtPhone.Text = phne;
txtAddressCon.Text = addrscon;
ddlStatePermanent.SelectedValue = statecon;
ddlCountryPermanent.SelectedValue = countrycon;
txtAddressPer.Text = addrsper;
ddlStateCommunication.SelectedValue = stateper;
ddlCountryCommunication.SelectedValue = countryper;
DataBind();
gridView();
}
else
{
lblMessage.Text = "*Please select any row to Update";
}
}
}
protected void updateButton_Click(object sender, EventArgs e)
{
string id = txtID.Text;
string fname = txtFirstName.Text;
string lname = txtLastName.Text;
string gendr = RdoGender.Text;
string mail = txtEmail.Text;
string phne = txtPhone.Text;
string addrscon = txtAddressCon.Text;
string statecon = ddlStatePermanent.SelectedItem.Value;
string countrycon = ddlCountryPermanent.SelectedItem.Value;
string addrsper = txtAddressCon.Text;
string stateper = ddlStateCommunication.SelectedItem.Value;
string countryper = ddlCountryCommunication.SelectedItem.Value;
SqlConnection con = con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("proc_UpdateRegisters", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#FirstName", fname);
cmd.Parameters.AddWithValue("#LastName", lname);
cmd.Parameters.AddWithValue("#Gender", gendr);
cmd.Parameters.AddWithValue("#Email", mail);
cmd.Parameters.AddWithValue("#Phone", phne);
cmd.Parameters.AddWithValue("#ContactAddres", addrscon);
cmd.Parameters.AddWithValue("#ContactState", statecon);
cmd.Parameters.AddWithValue("#ContactCountry", countrycon);
cmd.Parameters.AddWithValue("#CommunicationAddress", addrsper);
cmd.Parameters.AddWithValue("#CommunicationState", stateper);
cmd.Parameters.AddWithValue("#CommunicationCountry", countryper);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
DataTable dt = new DataTable();
cmd.CommandType = CommandType.StoredProcedure;
con.Close();
gridView();
}
// row delete
protected void btnDelete_Click(object sender, EventArgs e)
{
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows[i].
Cells[0].FindControl("radID");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
DeleteMultipleRecords(idCollection);
GridView1.DataBind();
}
else
{
lblMessage.Text = "*Please select any row to delete";
}
DataBind();
gridView();
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from Registers" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
protected void polyuria2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
var peradrs = txtAddressCon.Text;
var stat = ddlStatePermanent.SelectedIndex;
var contry = ddlCountryPermanent.SelectedIndex;
txtAddressPer.Text = peradrs;
ddlStateCommunication.SelectedIndex = stat;
ddlCountryCommunication.SelectedIndex = contry;
}
}
}
}
This is because the ViewState unable to maintain CheckBox state from GridView column. Easiest solution will be:
Add 'OnCheckedChanged' and 'OnDataBinding' event for checkbox column
<ItemTemplate>
<asp:CheckBox ID="radID" runat="server" OnCheckedChanged="radID_CheckedChanged" OnDataBinding="radID_DataBinding" />
</ItemTemplate>
Next step will be implement these events:
protected void radID_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
if (checkbox.Checked)
{
ViewState[checkbox.UniqueID] = true;
}
else
{
ViewState.Remove(checkbox.UniqueID);
}
}
protected void radID_DataBinding(object sender, EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
checkbox.Checked = ViewState[checkbox.UniqueID] != null;
}
Please let me know, if this helps.
i have a 3 tables: Section,Class and Student...now i want to loading the studentName on the dropdownlist based on selection Class with selecting section in dropdown list[Here Section Field,Class Field will b select by dropdownlist and StudentName also show in to the dropdownlist]
Here is my Table preview
SectionEnty
Id,SectionTitle,Capacity
ClassEntry
Id,ClassTitle,SectionId
StudentInfo
Id,FullName,ClassId,Section
it will b very helpful for me. If any one help me at this situation because i am all ready tried but its not working because of multiple index handling.
ASPX:
<asp:DropDownList ID="classdropdown" runat="server" OnSelectedIndexChanged="classdropdown_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList ID="sectiondropdown" runat="server" OnSelectedIndexChanged="sectiondropdown_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList ID="studentnamedropdown" runat="server" />
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.LoadClassDropdown();
}
}
// set initial values
private void LoadClassDropdown()
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Id,SectionTitle FROM SectionEnty", "your connection string"))
{
using (DataSet ds = new DataSet())
{
da.SelectCommand.Connection.Open();
da.Fill(ds);
da.SelectCommand.Connection.Close();
classdropdown.DataSource = ds;
classdropdown.DataValueField = "Id";
classdropdown.DataTextField = "SectionTitle";
classdropdown.DataBind();
}
}
}
protected void classdropdown_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Id,ClassTitle FROM ClassEntry WHERE SectionId = #SectionId", "your connection string")
{
da.SelectCommand.Parameters.Add(new SqlParameter("#SectionId", sectiondropdown.SelectedValue));
using (DataSet ds = new DataSet())
{
da.SelectCommand.Connection.Open();
da.Fill(ds);
da.SelectCommand.Connection.Close();
sectiondropdown.DataSource = ds;
sectiondropdown.DataValueField = "Id";
sectiondropdown.DataTextField = "ClassTitle";
sectiondropdown.DataBind();
}
}
}
protected void sectiondropdown_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Id,FullName FROM StudentInfo WHERE ClassId = #ClassId", "your connection string"))
{
da.SelectCommand.Parameters.Add(new SqlParameter("#ClassId", classdropdown.SelectedValue));
using (DataSet ds = new DataSet())
{
da.SelectCommand.Connection.Open();
da.Fill(ds);
da.SelectCommand.Connection.Close();
studentnamedropdown.DataSource = ds;
studentnamedropdown.DataValueField = "Id";
studentnamedropdown.DataTextField = "FullName";
studentnamedropdown.DataBind();
}
}
}
Now your studentnamedropdown contains the list for the selected class and section.
Any questions, let me know...
I have two dynamically populated radio button lists. The first one gets populated on a button click, the other one on the change event of the first radio button list. The problem is only with the second list. The issue is that I am not able to retrieve the changed value of the second radio button list in the InsertButton_Click method(marked by **). It always returns the default index value i.e 0. I don't have anything in page_load event. I read quite a few similar questions but none seem to help. Please guide. Below is the asp and c# code for the same:
ASP:
<asp:Button id="SaveButton"
Text="Save"
runat="server" onclick="SaveButton_Click">
</asp:Button>
<asp:Button id="VisualiseButton"
Text="Visualise"
runat="server" onclick="VisualiseButton_Click">
</asp:Button>
<!--<hr />-->
<asp:RadioButtonList id="RadioButtonList2" runat="server" Visible="false"
onselectedindexchanged="RadioButtonList2_SelectedIndexChanged" ></asp:RadioButtonList>
<asp:RadioButtonList id="RadioButtonList1" runat="server" Visible="false" ></asp:RadioButtonList>
<asp:Button id="SaveToDBButton"
Text="Insert"
runat="server" Visible="false" onclick="InsertButton_Click">
C#:
protected void SaveButton_Click(object sender, EventArgs e)
{
String selQuery = "SELECT id, name FROM categories";
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(selQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
RadioButtonList2.DataSource = dt;
RadioButtonList2.DataTextField = "name";
RadioButtonList2.DataValueField = "id";
RadioButtonList2.DataBind();
RadioButtonList2.RepeatColumns = 3;
RadioButtonList2.AutoPostBack = true;
RadioButtonList2.Visible = true;
}
catch (SqlException ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}
}
protected void RadioButtonList2_SelectedIndexChanged(object sender, EventArgs e)
{
String catId = RadioButtonList2.SelectedValue;
SqlCommand cmdselect = new SqlCommand("SELECT DISTINCT categoryId, linkTablesCategories.tableName, tableDescription FROM linkTablesCategories, tableDescriptions where linkTablesCategories.tableName = tableDescriptions.tableName and categoryId ='" + catId + "'");
RadioButtonList1.Items.Clear();
try
{
con.Open();
cmdselect.Connection = con;
SqlDataReader dar = cmdselect.ExecuteReader();
if (dar.HasRows)
{
while (dar.Read())
{
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
li.Attributes.Add("title", dar["tableDescription"].ToString());
RadioButtonList1.Items.Add(li);
}
}
RadioButtonList1.Visible = true;
SaveToDBButton.Visible = true;
}
catch (SqlException ex)
{
//lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
}
protected void InsertButton_Click(object sender, EventArgs e)
{
String tableId="";
**tableId = RadioButtonList1.SelectedItem.Text;**
String path = Server.MapPath("~/");
string filepath = path + Session["filepath"].ToString();
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = tableId;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
it was with the line:
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
The categoryId was a constant value and thus the issue, again my bad.
Thanks