Copying one datatable selected column to another data table - asp.net

I have a datatable, then I have all the column names of the datatable as checkbox, I want to display only those column records, for which user selected from the checkbox:
Below is the code, but I am not getting the desired result
var values = "";
string clmnm = "";
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected)
{
values += interestedIN.Items[i].Value + ",";
}
}
values = values.TrimEnd(',');
string[] words = values.Split(',');
DataTable dt = new DataTable();
dt = (DataTable)Session["dataset"];
DataTable dt1 = new DataTable();
foreach (string word in words)
{
dt1.Columns.Add(word, typeof(string));
if (clmnm == string.Empty)
{
clmnm = word.Trim();
}
else
{
clmnm += "," +word.Trim();
}
}
foreach (DataRow dr in dt.Rows)
{
string[] split = clmnm.Split(',');
int j =0;
string str = "";
string str2 = "";
while( j < split.Length)
{
str = split[j].ToString();
if (str2 == string.Empty)
{
str2 = "dr[\""+str.ToString()+"\"]";
}
else
{
str2 += "," + "dr[\""+str.ToString()+"\"]";
}
j+=1;
}
dt1.Rows.Add(str2);
}
then I am trying to export the result as an excel sheet: but getting the below excel sheet:

There is a lot of changes to be done to your code. Lets begin with selected columns from CheckBoxList. Try using List or Arrays to store which columns that user wants. Like
List<string> columns = new List<string>();
Then store the selected columns into the columns list. Then you need to add columns to your new DataTable dt1. As,
DataTable dt1 = new DataTable();
for (int i = 0; i < interestedIN.Items.Count; i++)
{
if (interestedIN.Items[i].Selected) //If user selected this columns checkbox.
{
columns.Add(interestedIN.Items[i].Text.Trim()); //Storing values to List.
dt1.Columns.Add(interestedIN.Items[i].Text.Trim()); //Adding columns to the DataTable.
}
}
Then you can loop through your original DataTable dt and store the values as below.
foreach (DataRow dr in dt.Rows)
{
DataRow dr1 = dt1.NewRow(); // Create new row which should have identical structure for inserting.
foreach(string col in columns)
{
dr1(col) = dr(col);
}
dt1.Rows.Add(dr1); //Add the row with the contents to the table.
}

Related

Dynamically created textbox value in gridview looping issue

In the below code i have created dynamic textbox in grid and i am saving the values in database .In my case there is only two rows created in gridview but in database it is saving 4 rows.Pls help me to solve the issue.
TestSchool.SchoolBusinessLyr.SchoolBizClient Grade = new TestSchool.SchoolBusinessLyr.SchoolBizClient();
System.Collections.Generic.Dictionary<string, string> AssignGrade = new System.Collections.Generic.Dictionary<string, string>();
foreach (GridViewRow row in gdassignmark.Rows)
{
int rowIndex = 0;
for (int i = 0; i < gdassignmark.Rows.Count; i++)
{
//extract the TextBox values
TextBox Sa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtsa");
TextBox fa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtfa");
// var SubjectID = gdassignmark.DataKeys[rowIndex]["SubjectID"] as string;
String cellText = row.Cells[0].Text;
String cellText1 = row.Cells[2].Text;
if (cellText != string.Empty)
{
if (fa.Text == "0")
{
int faval = int.Parse(fa.Text);
int mark = (faval / 40) * 100;
string strmark = mark.ToString();
AssignGrade.Add("BranchID", dpbranch.SelectedValue);
AssignGrade.Add("Academicyear", dpacademicyear.SelectedValue);
AssignGrade.Add("ExamID", dpExamName.SelectedValue);
AssignGrade.Add("ClassID", dpClassName.SelectedValue);
AssignGrade.Add("SectionID", "1");
AssignGrade.Add("SubjectID", cellText.ToString());
AssignGrade.Add("StudentID", dpStudentName.SelectedValue);
AssignGrade.Add("FA", Sa.Text);
AssignGrade.Add("SA", "");
AssignGrade.Add("FAandSA", (strmark));
Grade.InsertStudentGrade(AssignGrade);
}}
You are looping through the Rows twice. Assuming that Rows[i]Cells[i] is correct you can change your code to not loop through all rows for each row:
//foreach (GridViewRow row in gdassignmark.Rows)
//{
int rowIndex = 0;
for (int i = 0; i < gdassignmark.Rows.Count; i++)
{
GridViewRow row = gdassignmark.Rows[i]
//Do your stuff here
}
//}
You are looping over your gridview twice
Remove outer foreach so your code should look like this
TestSchool.SchoolBusinessLyr.SchoolBizClient Grade
= new TestSchool.SchoolBusinessLyr.SchoolBizClient();
System.Collections.Generic.Dictionary<string, string> AssignGrade
= new System.Collections.Generic.Dictionary<string, string>();
for (int i = 0; i < gdassignmark.Rows.Count; i++)
{
//extract the TextBox values
TextBox Sa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtsa");
TextBox fa = (TextBox)gdassignmark.Rows[i].Cells[i].FindControl("txtfa");
// var SubjectID = gdassignmark.DataKeys[rowIndex]["SubjectID"] as string;
String cellText = row.Cells[0].Text;
String cellText1 = row.Cells[2].Text;
if (cellText != string.Empty)
{
if (fa.Text == "0")
{
int faval = int.Parse(fa.Text);
int mark = (faval / 40) * 100;
string strmark = mark.ToString();
AssignGrade.Add("BranchID", dpbranch.SelectedValue);
AssignGrade.Add("Academicyear", dpacademicyear.SelectedValue);
AssignGrade.Add("ExamID", dpExamName.SelectedValue);
AssignGrade.Add("ClassID", dpClassName.SelectedValue);
AssignGrade.Add("SectionID", "1");
AssignGrade.Add("SubjectID", cellText.ToString());
AssignGrade.Add("StudentID", dpStudentName.SelectedValue);
AssignGrade.Add("FA", Sa.Text);
AssignGrade.Add("SA", "");
AssignGrade.Add("FAandSA", (strmark));
Grade.InsertStudentGrade(AssignGrade);
}
}

ASP.NET Dynamically add rows into existing Table while looping through XML nodes

What im trying to do is to populate an empty Table with cells and the number of cells per row is 4 and the number of all cells is the number of nodes in btnNode
The empty table ID = "MainTable"
and so far i created this but it seems i get an error in
TableRowCollection rows = new TableRowCollection();
has no constructors defined.Searched in google and didnt find help to solve this issue
Here is my code :
private void linkBTN_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
string text = btn.Text.ToString();
XmlDocument clickDoc = new XmlDocument();
clickDoc.Load(Server.MapPath("~/ProductShow.xml"));
XmlNodeList btnNode = clickDoc.SelectNodes("products/" + text.ToString() + "/*");
int count = btnNode.Count;
TableRowCollection rows = new TableRowCollection();
if (count < 4)
{
TableRow row = new TableRow();
rows.Add(row);
}
else
{
for (int i = 0; i < count / 4; i++)
{
TableRow row = new TableRow();
rows.Add(row);
}
}
int j = 1;
foreach (XmlNode node in btnNode)
{
//TableRow row = new TableRow();
TableCell cell = new TableCell();
cell.CssClass = "Cell";
LinkButton linkbtn = new LinkButton();
linkbtn.Text = node.InnerText;
linkbtn.Attributes.Add("runat", "server");
Image img = new Image();
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl("<br/>"));
cell.Controls.Add(img);
rows[j].Cells.Add(cell);
j++;
}
foreach (TableRow row in rows)
{
MainTable.Rows.Add(row);
}
}

Unable to add data in a datatable asp.net

DataRow new_row = tb11.NewRow();
for (i = 0; i < 8; i++)
{
new_row[i] = tb11.Rows[0][i].ToString();
}
tb11.Rows.Add(new_row);
I am running the following code to add data to a existing datatable but no data is inserted into the databale.
DataTable dt = ds3.Tables["FormName"];
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
dt.Columns[2].ColumnName = "EmpId";
dt.Columns[3].ColumnName = "EmpName";
dt.Columns[4].ColumnName = "Branch";
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["EmpId"] = UID;
dt.Rows[i]["EmpName"] = EmpName;
dt.Rows[i]["Branch"] = Zone;
}
dt.AcceptChanges();
foreach (DataRow row in dt.Rows)
{
string NEmpId = dt.Rows[j]["EmpId"].ToString();
string NEmpName = dt.Rows[j]["EmpName"].ToString();
}
you are calling newrow() on the same table tb11 from where you get your source data and adding new row in same table tb11. Also tb11.Rows[0] will access first row everytime

Editable gridview based on list

Is it possible to create a gridview based on a list? I have the following list:
ID = 1
Name = John
Zip = 33141
ID = 2
Name = Tim
Zip = 33139
I want to be able to create an editable gridview with this list
When i bind it to the grid view, it seems to put everyting in one column, and i can't figure out how to get it to seperate it into different columns
Here is my code for setting the DataSource of the GridView:
DataTable table = ConvertListToDataTable(personList);
GridView1.DataSource = table;
GridView1.DataBind();
static DataTable ConvertListToDataTable(List<string> list)
{
// New table.
DataTable table = new DataTable();
// Get max columns.
int columns = 7;
// Add columns.
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
}
// Add rows.
foreach (var rd in list)
{
table.Rows.Add(rd);
}
return table;
}
Here is an example:
private class Person
{
int m_iID;
string m_sName;
string m_sZip;
public int ID { get { return m_iID; } }
public string Name { get { return m_sName; } }
public string Zip { get { return m_sZip; } }
public Person(int iID, string sName, string sZip)
{
m_iID = iID;
m_sName = sName;
m_sZip = sZip;
}
}
private List<Person> m_People;
private void ConvertListToDataTable(List<Person> People)
{
DataTable table = new DataTable();
DataColumn col1 = new DataColumn("ID");
DataColumn col2 = new DataColumn("Name");
DataColumn col3 = new DataColumn("Zip");
col1.DataType = System.Type.GetType("System.String");
col2.DataType = System.Type.GetType("System.String");
col3.DataType = System.Type.GetType("System.String");
table.Columns.Add(col1);
table.Columns.Add(col2);
table.Columns.Add(col3);
foreach (Person person in People)
{
DataRow row = table.NewRow();
row[col1] = person.ID;
row[col2] = person.Name;
row[col3] = person.Zip;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
}

Get Index of the Excel Sheet using asp.net

I am using the following code to extract the sheet names from excel: (See attached code)
But the data is returned sorted by the NAMES of the sheets, and this is the issue. I need to extract the name of the first sheet, by index.
How can I do this?
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + fileSavePath + newFileName + ".xls; Extended Properties='Excel 8.0;HDR=NO;'";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
// Get the data table containg the schema guid.
DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = "Sheet1$";
if (dt != null) {
try {
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow rows in dt.Rows) {
excelSheets[i] = rows["TABLE_NAME"].ToString();
i++;
}
sheetName = excelSheets[0];
}
catch {
sheetName = "Sheet1$";
}
}
try spread Sheet Gear third party component
http://www.spreadsheetgear.com

Resources