2
Answers

Unable to get excel file data in gridview please help me ...

Photo of Web Infotech

Web Infotech

7y
173
1
private void btnFileUpload_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Excel Files|*.xls;*.xlsx"; // file types, that will be allowed to upload
dialog.Multiselect = false; // allow/deny user to upload more than one file at a time
if (dialog.ShowDialog() == DialogResult.OK) // if user clicked OK
{
String path = dialog.FileName; // get name of file
using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open), new UTF8Encoding())) // do anything you want, e.g. read it
{
// ...
}
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(constr);
System.Data.OleDb.OleDbDataAdapter MyDataAdapter = new System.Data.OleDb.OleDbDataAdapter("Select MobileNo from [Sheet1$]", con);
System.Data.DataTable dt = new System.Data.DataTable();
MyDataAdapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
dataGridView1.DataSource = dt;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Answers (2)

0
Photo of tsuman_in
NA 152 0 21y
Just so you know, you should never loop through to build strings, they are immutable and this gets very costly. Use: StringBuilder sb = new StringBuilder(); foreach(Control co in r.Cells[2].Controls) { if (co.GetType() == typeof(Checkbox)) sb.Append((Checkbox)co).Checked.ToString()+"\n"; } string output = sb.ToString();
0
Photo of thed0ct0r
NA 48 0 21y
foreach(Control co in r.Cells[2].Controls) { if (co.GetType().Name.ToString() == "Checkbox") TextBox1.Text+= ((Checkbox)co).Checked.ToString()+"\n"; }
0
Photo of John O Donnell
NA 3.5k 1.4m 21y
Always the same...you post a question then work it out!! the answer was to use the uniqueid of the control and then use findcontrol to return it. Also needed to cast the control etc. now it all works and heres the code foreach(Control co in r.Cells[2].Controls) { CheckBox cb=(CheckBox)this.FindControl(co.UniqueID); TextBox1.Text=TextBox1.Text+cb.Checked.ToString()+"\n"; }